package com.cn.bulu.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayFundTransOrderQueryModel;
import com.alipay.api.domain.AlipayFundTransToaccountTransferModel;
import com.alipay.api.request.AlipayFundTransOrderQueryRequest;
import com.alipay.api.request.AlipayFundTransToaccountTransferRequest;
import com.alipay.api.response.AlipayFundTransOrderQueryResponse;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.cn.bulu.constant.CustomerType;
import com.cn.bulu.constant.PayMethod;
import com.cn.bulu.constant.TypeOfIndent;
import com.cn.bulu.constant.WorkerType;
import com.cn.bulu.dao.*;
import com.cn.bulu.pojo.*;
import com.cn.bulu.pojo.Dictionary;
import com.cn.bulu.service.*;
import com.cn.bulu.utils.*;
import com.cn.bulu.utils.ClothCurtain.Arith;
import com.cn.bulu.utils.MD5Utils.MD5Utils;
import com.cn.bulu.utils.alipay.config.AlipayConfig;
import com.cn.bulu.utils.alipay.util.AlipayParams;
import com.cn.bulu.utils.jiguang.Jiguang;
import com.cn.bulu.utils.kuaiDI.KdApiOrderDistinguish;
import com.cn.bulu.utils.kuaiDI.KdniaoTrackQueryAPI;
import com.cn.bulu.utils.redis.JedisUtil;
import com.google.gson.Gson;
import org.apache.commons.collections.map.HashedMap;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.interfaces.RSAPrivateKey;
import java.text.DecimalFormat;
import java.util.*;

@Service("customerService")
public class CustomerServiceImpl implements CustomerService {

	private static Logger logger = Logger.getLogger(CustomerServiceImpl.class);

	@Resource
	private CustomerDao customerDao;
	@Resource
	private GoodsDao goodsDao;
	@Resource
	private IndentDao indentDao;
	@Resource
	private WorkerDao workerDao;
	@Resource
	private BankCardDao bankCardDao;
	@Resource
	private SampleDao sampleDao;
	@Resource
	private UserDao userDao;
	@Resource
	private WorkerWalletRecordService workerWalletRecordService;
	@Resource
	private CustomerWalletRecordService customerWalletRecord;
	@Resource
	private CustomerWalletRecordService customerWalletRecordService;
	@Resource
	private PriceService priceService;
	@Resource
	private CustomerWalletRecordDao customerWalletRecordDao;
	@Autowired
	private IndentService indentService;

	/**
	 * 注册鹿客家居
	 */
	public BuluResult register(String nickName, String account, String referrer, String gender) {
		// 返回参数准备
		BuluResult buluResult = new BuluResult();
		// 解密获取电话号码和密码的集合
		JSONObject objectAccount = getAccountMap(account);
		// 解密失败,直接返回数据
		if (null == objectAccount) {
			buluResult.setStatus(1);
			buluResult.setMessage("账号或密码无法获取,请检查填写数据");
			return buluResult;
		}
		// 获取解密后的电话和密码
		String phone = objectAccount.getString("phone");
		String password = objectAccount.getString("password");
		// 检验注册参数
		buluResult = checkRegistParams(nickName, phone, password);
		// 参数如有不合格直接返回数据
		if (buluResult.getStatus() == 1) {
			return buluResult;
		}
		// 再次判断手机号码是否已经注册
		buluResult = isPhone(phone);
		if (buluResult.getStatus() == 1) {
			return buluResult;
		}
		// 整合参数插入数据库返回注册成功
		Map<Object, Object> map = new HashMap<Object, Object>();
		map.put("phone", phone);
		map.put("nickName", nickName);
		// 每个人都有一个配合密码加密的盐
		String weiyi = MD5Utils.getUUID();
		map.put("weiyi", weiyi);
		// 保存在数据库中的密码使用MD5加密
		map.put("password", MD5Utils.MD5(password + weiyi));
		map.put("referrer", referrer);
		map.put("gender", gender);
		customerDao.insertCustomer(map);
		buluResult.setStatus(0);
		buluResult.setMessage("注册成功");
		return buluResult;
	}

	/**
	 * 验证用户密码
	 * 
	 * @param phone
	 * @param password
	 * @param map
	 * @return
	 */
//	public BuluResult checkAccount(String phone, String password, Map<String, Object> map) {
//		BuluResult buluResult = new BuluResult();
//		// 根据电话号码获取该电话号码对应的顾客信息
//		Map<String, Object> customer = customerDao.selectMessage(map);
//		// 判断是否根据电话号码找到对应的账户信息
//		if (null == customer) {
//			buluResult.setStatus(1);
//			buluResult.setMessage("改手机号尚未注册,赶紧去注册哦");
//			return buluResult;
//		}
//		// 判断该顾客的状态,1表明该顾客账号已经被停用
//		if ((Integer) customer.get("isDisable") == 1) {
//			buluResult.setStatus(1);
//			buluResult.setMessage("改账户已经被停用,如需重新使用请联系客服");
//			return buluResult;
//		}
//		// 如账号仍在继续使用,比较密码
//		String weiyi = (String) customer.get("weiyi");
//		String dataBasePassword = (String) customer.get("password");
//		// 密码比对成功
//		if (dataBasePassword.equals(MD5Utils.MD5(password + weiyi))) {
//			buluResult.setStatus(0);
//			buluResult.setData(customer);
//			buluResult.setMessage("密码正确");
//		} else {
//			buluResult.setStatus(1);
//			buluResult.setMessage("输入账号或密码有误,请重新输入");
//		}
//		return buluResult;
//	}

	/**
	 * 修改密码
	 * 
	 * @param account
	 * @return
	 */
	public BuluResult updatePassword(String account) {
		// 返回参数准备
		BuluResult buluResult = new BuluResult();
		// 解密获取账号和密码集合
		JSONObject object = getAccountMap(account);
		if (null == object) {
			buluResult.setStatus(1);
			buluResult.setMessage("登录获取电话或者密码失败,请检查填写的账号或者密码");
			return buluResult;
		}
		// 账号和密码
		String phone = object.getString("phone");
		String password = object.getString("password");
		// 检验参数
		buluResult = checkRegistParams("updateNeedChectParam", phone, password);
		if (buluResult.getStatus() == 1) {
			return buluResult;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("phone", phone);
		// 重新获取盐
		String weiyi = MD5Utils.getUUID();
		map.put("weiyi", weiyi);
		map.put("password", MD5Utils.MD5(password + weiyi));
		customerDao.updatePassword(map);
		buluResult.setStatus(0);
		return buluResult;
	}


    
    //二维码扫描注册
    @Override
    public BuluResult registWeb(HttpSession session,String nickName,String phone,String password,String referrer,String gender,Integer identity) throws Exception{
        // 返回参数准备
        BuluResult buluResult = new BuluResult();
    	  // 检验注册参数
        buluResult = checkRegistParams(nickName, phone, password);
        // 参数如有不合格直接返回数据
        if (buluResult.getStatus() == 1) {
            return buluResult;
        }
    	//RSA解密
    	RSAPrivateKey privateKey = (RSAPrivateKey) session.getAttribute("privateKey");
    	password=RSAUtils.decryptByPrivateKey(password, privateKey);// 解密后的密码,password
    	//检查是否已经注册
    	BuluResult brs=isPhone(phone);
    	if(brs.getStatus()==1){
    		//已经注册
		   buluResult.setStatus(0);
	       buluResult.setMessage("用户已注册");
	       return buluResult;
    	}
    	
        // 整合参数插入数据库返回注册成功
        Map<Object, Object> map = new HashMap<Object, Object>();
        map.put("phone", phone);
        map.put("nickName", nickName);
        // 每个人都有一个配合密码加密的盐
        String weiyi = MD5Utils.getUUID();
        map.put("weiyi", weiyi);
        // 保存在数据库中的密码使用MD5加密
        map.put("password", MD5Utils.MD5(password + weiyi));
        
        map.put("referrer", referrer);
        map.put("gender", gender);
        map.put("vertification",identity);
        customerDao.insertCustomer(map);
        buluResult.setStatus(0);
        buluResult.setMessage("注册成功");
        return buluResult;
    }
    
    @Override
    public Map<String,Object> isCustomerOrdered(Integer indentId){
    	return customerDao.isCustomerOrdered(indentId) ;
    }
    
    
    
    

    /**
     * 检验注册参数是否符合公司规定,其中nickName,phone,password不能为空或者null以及其他的无用数据
     *
     * @param nickName 注册昵称
     * @param phone    注册电话号码
     * @param password 注册密码
     * @return
     */
    private BuluResult checkRegistParams(String nickName, String phone, String password) {
        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        if (BuLuStringUtils.isEmpty(nickName)) {
            buluResult.setStatus(1);
            buluResult.setMessage("注册昵称不能为空");
            return buluResult;
        }
        if (BuLuStringUtils.isEmpty(phone)) {
            buluResult.setStatus(1);
            buluResult.setMessage("电话号码不能为空");
            return buluResult;
        }
        if (BuLuStringUtils.isEmpty(password)) {
            buluResult.setStatus(1);
            buluResult.setMessage("密码不能为空");
        }
        return buluResult;
    }

    /**
     * 对账号和密码进行解密
     *
     * @param account
     * @return
     */
    private JSONObject getAccountMap(String account) {
        JSONObject map = new JSONObject();
        try {
            account = AESCipher.aesDecryptString(account, Constant.ENCRYPTKEY);
            map = JSONObject.parseObject(account);
        } catch (Exception e) {
            return null;
        }
        return map;
    }

    /**
     * 判断手机号是否已经存在
     */
    public BuluResult isPhone(String phone) {
        int number = customerDao.getCustomerNumber(phone);
        BuluResult buluResult = new BuluResult();
        if (number == 0) {
            buluResult.setStatus(0);
        } else {
            buluResult.setStatus(1);
            buluResult.setMessage("该手机号已经注册!");
        }
        return buluResult;
    }

    /**
     * 顾客登录
     */
    public BuluResult login(String account, HttpServletRequest request) {
        // 返回数据准备
        BuluResult buluResult = getAccountMap2(account);
        if (buluResult != null && (buluResult.getStatus() == 0)) {
            @SuppressWarnings("unchecked")
            Map<String, Object> map = (Map<String, Object>) (buluResult.getData());
            if (map != null) {
                String phone = map.get("phone").toString();
                String password = map.get("password").toString();
                // 判断是顾客登录还是经销商登录
                return phone.length() >= 11 ? customerLogin(phone, password, map, request)
                        : agencyLogin(phone, password, map, request);
            }
        }
        return buluResult;
    }

    private BuluResult getAccountMap2(String account) {
        BuluResult buluResult = new BuluResult();
        // 对account进行解密
        JSONObject object = getAccountMap(account);
        // 解密失败直接返回数据
        if (null == object) {
            buluResult.setStatus(1);
            buluResult.setMessage("登录获取电话或者密码失败,请检查填写的账号或者密码");
            return buluResult;
        }
        // 获取账号和密码
        String phone = object.getString("phone");
        String password = object.getString("password");
        // 登录参数验证
        buluResult = checkRegistParams("loginNeedCheckParam", phone, password);
        // 参数如有不合格直接返回数据
        if (buluResult.getStatus() == 1) {
            buluResult.setStatus(1);
            buluResult.setMessage("登录获取电话或者密码为空");
            return buluResult;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("phone", phone);
        map.put("password", password);
        buluResult.setStatus(0);
        buluResult.setData(map);
        return buluResult;
    }
    

    /**
     * 经销商子账户登录
     *
     * @param phone    输入的子账户的customerId
     * @param password 输入的子账户的密码
     * @param map      保存有账户和密码的集合
     * @param request
     * @return
     */
    private BuluResult agencyLogin(String phone, String password, Map<String, Object> map,
                                   HttpServletRequest request) {
        map.put("customerId", phone);
        map.remove("phone");
        return customerLogin(phone, password, map, request);
    }

    /**
     * 验证用户密码
     *
     * @param phone
     * @param password
     * @param map
     * @return
     */
    private BuluResult checkAccount(String phone, String password, Map<String, Object> map) {
        BuluResult buluResult = new BuluResult();
        // 根据电话号码获取该电话号码对应的顾客信息
        Customer customer = customerDao.selectMessage(map);
        // 判断是否根据电话号码找到对应的账户信息
        if (null == customer) {
            buluResult.setStatus(3);
            buluResult.setMessage("该手机号尚未注册,赶紧去注册哦");
            return buluResult;
        }
        // 判断该顾客的状态,1表明该顾客账号已经被停用
        if (customer.getIsDisable() == 1) {
            buluResult.setStatus(1);
            buluResult.setMessage("该账户已经被停用,如需重新使用请联系客服");
            return buluResult;
        }
        // 如账号仍在继续使用,比较密码
        String weiyi = customer.getWeiyi();
        String dataBasePassword = customer.getPassword();
        // 密码比对成功
        if (dataBasePassword.equals(MD5Utils.MD5(password + weiyi))) {
            buluResult.setStatus(0);
            buluResult.setData(customer);
            buluResult.setMessage("密码正确");
        } else {
            buluResult.setStatus(1);
            buluResult.setMessage("输入账号或密码有误,请重新输入");
        }
        return buluResult;
    }

    /**
     * 顾客登录,手机号码不小于11位为顾客登录
     *
     * @param map     登录的手机号码
     * @param request 登录输入的密码
     * @return
     */
    private BuluResult customerLogin(String phone, String password, Map<String, Object> map,
                                     HttpServletRequest request) {
        BuluResult buluResult = checkAccount(phone, password, map);
        if (buluResult.getStatus() == 0) {
            @SuppressWarnings("unchecked")
            Customer customer0 = (Customer) buluResult.getData();
            Map<String,Object> customer = LuKeBeanUtil.beanToMap(customer0);
            // 0顾客登录 1经销商子账户登录
            customer.put("isChild", phone.length() >= 11 ? 0 : 1);
            List<Integer> list = new ArrayList<>();
            // 找打该顾客的收藏
            list.addAll(customerDao.selectCollectionDL((Integer) customer.get("customerId")));
            customer.put("shoucang", list);
            // String sign = MD5Utils.getUUID();
            String weiyi = (String) customer.get("weiyi");
            customer.put("sign", weiyi);
            // 登录成功,将顾客id放在reDis中
            JedisUtil.keepSessionIDForApp(weiyi, String.valueOf((Integer) customer.get
                    ("customerId")), 5);
            // 返回登录信息消除密码,顾客id,密码配合的盐
            customer.remove("password");
            customer.remove("weiyi");
            // 查询用户默认地址
            Map<String, Object> defaultAddress = customerDao.selectDefault((Integer) customer.get
                    ("customerId"));
            buluResult.setStatus(0);
            customer.put("customerAddress", defaultAddress);
            buluResult.setData(customer);
            return buluResult;
        } else {
            return buluResult;
        }
    }

    /**
     * 安装房间位置获取
     */
    public BuluResult getLocation() {
        List<Location> locations = customerDao.getLocation();
        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        buluResult.setData(locations);
        return buluResult;
    }

    /**
     * 功能：添加商品
     *
     * @param request
     * @param goods
     * @return
     */
    private Goods addGoods(HttpServletRequest request, Goods goods, Integer type, JSONArray accsList) {
        // type:0 成品帘1布艺帘2:配件
        Integer customerId = getIdFromRedis(request);
        goods.setIsCar(1); // 是否购物车
        goods.setType(type);// 商品类型
        goods.setCustomerId((int) customerId);
        goods.setGoodsPrice(0.0);
        if (type == 2) {// 是配件
            Double price = customerDao.selectPPrice(goods.getSampleId()); // 根据产品号查询配件价格
            if (goods.getAccessoriesTypeId() == 2 || goods.getAccessoriesTypeId() == 6) {// 直轨
                // 弯轨
               Double goodsPrice = price * goods.getNumber() * goods.getSaleNumber();
                if (goods.getAcc() != null && goods.getAcc().contains("魔术轨")) {// 代表包含魔术轨 则需再加一个商品 魔术轨
                    goodsPrice += goods.getSaleNumber() * customerDao.selectMoshugui();
                    goods.setAddpeijian(1);// 1加装了魔术轨 0没有加装魔术轨
                }
                goods.setGoodsPrice(goodsPrice);
            } else if (goods.getAccessoriesTypeId() == 1 || goods.getAccessoriesTypeId() == 5) {//罗马杆
                // 魔术轨
                Double goodsPrice = price * goods.getNumber() * goods.getSaleNumber();
                goods.setGoodsPrice(goodsPrice);
            } else if (goods.getAccessoriesTypeId() == 3 || goods.getAccessoriesTypeId() == 4) {//璧钩
                // 挂绳
                Double goodsPrice = price * goods.getNumber();
                goods.setGoodsPrice(goodsPrice);
            }
        }
        customerDao.insertCar(goods); // 存入数据库

        // 因业务需求，将购物车中的商品天加配件的功能暂时去掉，所以这里也不再向数据库添加配件
        // if (accsList != null) {
        // // 查找配件的值
        // for (int i = 0; i < accsList.size(); i++) {
        // Goods_special special = new Goods_special();
        // JSONObject accssJson = JSONObject.parseObject(accsList.getString(i));
        // if (accssJson.getInteger("sampleId") != null) {
        // Goods accs = LuKeBeanUtil.fromJSONObjectToBean(accssJson,
        // Goods.class);
        // accs.setIsCar(0);
        // accs.setCustomerId((int) customerId);
        // customerDao.insertCar(accs);
        // special.setAccessoriesType((String) (customerDao
        // .selectAccessoriesTypeById(customerDao.selectLeixing(accssJson.getInteger("sampleId")))
        // .get("accessoriesTypeContent")));
        // special.setAccId(accs.getGoodsId());
        // } else {
        // if (accssJson.getInteger("whatStructure") == 3) {
        // special.setAccessoriesType("魔术轨");
        // }
        // }
        // special.setWhatStructure(accssJson.getInteger("whatStructure"));
        // special.setGoodsId(goods.getGoodsId());
        // saveGoodsSpecial(special);
        // }
        // }
        return goods;
    }

    public void saveGoodsSpecial(Goods_special special) {
        customerDao.insertSpecial(special); // 添加
    }

    /**
     * 功能：添加到购物车 @
     */
    public BuluResult addCar(HttpServletRequest request, String goodsList) {
        BuluResult buluResult = new BuluResult();
        // 解析需要加入购物车的商品
        JSONArray list = JSONArray.parseArray(goodsList);
        if (list.size() <= 0 || list == null){
            buluResult.setStatus(1);
            buluResult.setMessage("没有添加任何数据！");
            return buluResult;
        }
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                JSONObject goodAndAcc = JSONObject.parseObject(list.get(i).toString());
                Integer type = null;
                if (goodAndAcc != null)
                    type = goodAndAcc.getInteger("type");
                // 保存商品
                Goods good = LuKeBeanUtil.fromJSONObjectToBean(JSONObject.parseObject
                                (goodAndAcc.getString("goods")),
                        Goods.class);
                JSONArray accsList = JSONArray.parseArray(goodAndAcc.getString("accs"));
                if (good != null) {
                    addGoods(request, good, type, accsList);
                }
            }
        }
        buluResult.setStatus(0);
        buluResult.setMessage("添加购物车成功！");
        return buluResult;
    }
    /**
     * 功能：重选款式
     *
     */
    @Transactional
    public BuluResult reselectStyle(HttpServletRequest request, Map<String, Object> map) {
        BuluResult buluResult = new BuluResult();
        Integer goodsId = (Integer) map.get("goodsId"); // 需要替换掉的原款式产品
        Integer sampleId = (Integer) map.get("sampleId"); // 新款式产品的ID

        Goods goods=goodsDao.selectGoodsById(goodsId);
        Sample sample = sampleDao.selectSampleById(sampleId);
        if(goods !=null && sample !=null){
            //置换原good对应的smpleId
            goods.setSampleId(sampleId);
            //计算goodsPrice
            if(sample.getType()==0){//布艺帘
            	Goods prices=null;
                if(goods.getStructure() !=null){
                    List<Goods_special> specials=null;
                    Goods_special specialContion=new Goods_special();
                    specialContion.setGoodsId(goodsId);
                    specials=customerDao.selectGoodsSpecialByGoodsId(specialContion);
                    if(specials!=null && specials.size()>0){
                        for(Goods_special special :specials){
                            if(special.getType()==0){
                                //0布
                                goods.setClothHigh(special.getHigh());
                                goods.setClothWide(special.getWide());
                            }else if(special.getType()==1){
                                //1纱
                                goods.setYarnHigh(special.getHigh());
                                goods.setYarnWide(special.getWide());
                            }
                        }
                        BuluResult b=priceService.calcCurtainPrice(goods);
                        if(b.getData()!=null)
                        	prices=(Goods) b.getData();
                            goods.setGoodsPrice(prices.getGoodsPrice());
                            goods.setSumBPrice(prices.getSumBPrice());
                            goods.setSumLPrice(prices.getSumLPrice());
                            goods.setSumShadingBprice(prices.getSumShadingBprice());
                            goods.setSumSPrice(prices.getSumSPrice());
                            goods.setSumPrice(prices.getGoodsPrice());                            
                    }
                }
                goodsDao.updateGoods(goods);       
                buluResult.setData(0);
                buluResult.setMessage("已选择新款式");
                return buluResult;
            } else if (sample.getType() == 1) {// 成品帘
                Map<String, Object> finishMap = new HashMap<>();
                finishMap.put("sampleId", sampleId);
                finishMap.put("finish", goodsDao.selectFinishedCurtain(goodsId));
                BuluResult b = priceService.getPriceOfFinish(JSON.toJSONString(finishMap));
                if(b.getStatus()==0)
                    goods.setGoodsPrice(Double.parseDouble((b.getData()==null
                            || "".equals(b.getData().toString())) ? "0.0" : b.getData().toString()));
                goodsDao.updateGoods(goods);
                buluResult.setData(0);
                buluResult.setMessage("已选择新款式");
                return buluResult;
            }else{//配件
                System.out.println("========配件没有重选款式的功能===========");
            }
        }
        buluResult.setData(1);
        buluResult.setMessage("选择失败");
        return buluResult;
    }
        /**
         * 点击加入收藏 sampleIdS="[1001,1002]"
         */

    public BuluResult addCollect(HttpServletRequest request, String sampleIdS) {
        Integer customerId = getIdFromRedis(request);
        BuluResult buluResult = new BuluResult();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("customerId", customerId);
        JSONArray list = JSONArray.parseArray(sampleIdS);
        Integer[] saIDS = customerDao.selectSampleId(customerId);
        for (int a = 0; a < list.size(); a++) {
            Integer sampleId = (Integer) list.get(a);
            boolean cf = true;
            for (int b = 0; b < saIDS.length; b++) {
                if (saIDS[b].equals(sampleId)) {
                    cf = false;
                }
            }
            if (cf) {
                map.put("sampleId", sampleId);
                customerDao.addCollect(map);
            }
        }
        buluResult.setStatus(0);
        return buluResult;

    }
    /**
     * 点击展示收藏
     */
    public BuluResult selectCollect(HttpServletRequest request) {
        BuluResult buluResult = new BuluResult();
        Integer customerId = getIdFromRedis(request);
        Integer[] sampleIDS = customerDao.selectSampleId(customerId);
        List<Sample> list = new ArrayList<Sample>();
        if (sampleIDS != null && sampleIDS.length != 0) {
            for (int a = 0; a < sampleIDS.length; a++) {
                Sample sample = customerDao.selectOneSample(sampleIDS[a]);
                if (sample != null)
                    list.add(sample);
            }
            //向商品中添加满减优惠信息
            Double measureMoneyOff = customerDao.selectTerritoryByType(8).getMoney();
			Double installMoneyOff = customerDao.selectTerritoryByType(9).getMoney();
			for(int a=0; a<list.size();a++){
				list.get(a).setMeasureMoneyOff(measureMoneyOff);//满减测量费
				list.get(a).setInstallMoneyOff(installMoneyOff);//满减安装费
				if(list.get(a).getType()==0){//布艺
					Double Sprice = customerDao.selectSprice(list.get(a).getSampleId());
					if(Sprice!=null){
						list.get(a).setSsPrice(Sprice);//纱价格
					}
					if(list.get(a).getSwag()==1){//帘头：0没有  1有
						list.get(a).setLlPrice(customerDao.selectLprice(list.get(a).getSampleId()));//帘头价格
					}
				}
				if(list.get(a).getSeries()!=null){
					List<Sample> samples = customerDao.selectSeries(list.get(a).getSeries());
					for (Sample sample:samples) {
						sample.setMeasureMoneyOff(measureMoneyOff);
						sample.setInstallMoneyOff(installMoneyOff);
					}
					list.get(a).setSeriesList(samples);
				}
			}
            buluResult.setStatus(0);
            buluResult.setData(list);
            return buluResult;
        } else {
            buluResult.setStatus(1);
            buluResult.setMessage("暂无收藏商品!!!");
            return buluResult;
        }
    }
    /**
     * 删除收藏
     */
    public BuluResult deleteCollect(HttpServletRequest request, String sampleIdS) {
        BuluResult buluResult = new BuluResult();
        Integer customerId = getIdFromRedis(request);
        JSONArray list = JSONArray.parseArray(sampleIdS);
        for (int a = 0; a < list.size(); a++) {
            Integer sampleId = list.getInteger(a);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("customerId", customerId);
            map.put("sampleId", sampleId);
            customerDao.deleteCollection(map);
            map.clear();
        }
        buluResult.setStatus(0);
        buluResult.setMessage("删除成功!!!");
        return buluResult;
    }

    /**
     * 获取存放在redis中的id(该id在登录成功后保存在redis中,保存在数据库中5)
     *
     * @param request
     * @return
     */
    private Integer getIdFromRedis(HttpServletRequest request) {
        // 获取sign
        String sign = (String) request.getParameter("sign");
        // 调用redis工具类获取想要的idf
        Integer customerId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 5));
        // 返回数据
        return customerId;
    }

    /**
     * 展示购物车
     */
    public BuluResult showCar(HttpServletRequest request) {
        /* Integer customerId =getIdFromRedis(request); */
        // 获取sign
        String sign = (String) request.getParameter("sign");
        // 调用redis工具类获取想要的id
        Integer customerId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 5));
        BuluResult buluResult = new BuluResult();
        List<Map<String, Object>> list = customerDao.getCar((Integer) customerId);
        for (int b = 0; b < list.size(); b++) {
            list.get(b).put("acc", list.get(b).get("acc"));
            if (list.get(b).get("locationId") != null) {
                String locationContent = customerDao.selectLocation((Integer) list.get(b).get
                        ("locationId"));
                list.get(b).put("locationContent", locationContent);// 获取locationName
            }

            if (list.get(b).get("acc") != null && "魔术轨".equals((String) (list.get(b).get
                    ("acc")))) {
                list.get(b).put("magicRail",
                        Arith.mul((double) (list.get(b).get("saleNumber")),
                                customerDao.selectMoshugui()));
            }

            // 因业务需求，购物车商品不再有配件
            // List<Goods_special> goodsSpecialList =
            // customerDao.selectSpecial((int) goodsId);
            // List<Map<String, Object>> listAcces = new ArrayList<Map<String,
            // Object>>();
            // if (goodsSpecialList != null) {
            // for (int a = 0; a < goodsSpecialList.size(); a++) {
            // Map<String, Object> indexMap =
            // LuKeBeanUtil.beanToMap(goodsSpecialList.get(a));
            // Integer accId = (Integer) indexMap.get("accId");
            // if (accId != null && accId != 0) {
            // Map<String, Object> Img = customerDao.selectSampleImg(accId);
            // if (Img != null)
            // indexMap.putAll(Img);
            // }
            // listAcces.add(indexMap);
            // }
            // }
            // list.get(b).put("acces", listAcces);
        }
        List<Map<String, Object>> list2 = customerDao.getCar2((Integer) customerId);
        list.addAll(list2);
        buluResult.setStatus(0);
        buluResult.setData(list);
        return buluResult;
    }

    /**
     * 功能：删除购物车中的产品
     */
    public BuluResult deleteCar(String goodsIds) {
        BuluResult buluResult = new BuluResult();
        JSONArray parseArray = JSONArray.parseArray(goodsIds);
        for (int i = 0; i < parseArray.size(); i++) {
            System.err.println("===>"+(parseArray.get(i) instanceof String
                    ? "String 类型" : parseArray.get(i) instanceof Integer ? "Integer 类型" : "其他类型"));
            customerDao.deleteGoodOfCar(parseArray.getInteger(i));
        }
        buluResult.setStatus(0);
        return buluResult;
    }

    /**
     * 把购物车中的商品添加到order(全是配件) //goods=[,,,]多个goodsId--暂时无用
     */
    public BuluResult insertOrderOfNoIndent(HttpServletRequest request, String goods) {
        Integer customerId = getIdFromRedis(request);
        JSONArray goods2 = JSONArray.parseArray(goods);
        Double orderPrice = 0.0;
        for (int a = 0; a < goods2.size(); a++) {
            Double goodsPrice = customerDao.selectGoodsPrice((Integer) goods2.get(a));
            orderPrice += goodsPrice;
        }
        // 生成订单
        Date beginTime = new Date();
        Orders orders = new Orders();
        orders.setBeginTime(beginTime);
        orders.setCustomerId(customerId);
        orders.setOrderPrice(orderPrice);
        orders.setStatus(1);
        customerDao.insertOrderOfNoIndent(orders);
        for (int b = 0; b < goods2.size(); b++) {
            Map<String, Object> map = new HashMap<>();
            map.put("orderId", orders.getOrderId());
            map.put("goodsId", (Integer) goods2.get(b));
            customerDao.updateGOrderId(map);
        }
        Map<String, Object> map = customerDao.selectOrderX(orders.getOrderId());
        List<Map<String, Object>> list = customerDao.getSampleDetailByOrderId2(orders.getOrderId());
        map.put("samples", list);
        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        buluResult.setData(map);
        return buluResult;
        // Object customerId = request.getSession().getAttribute("customerId");
        // JSONObject goods2 = JSONObject.parseObject(goods);
        // JSONArray goodsIdsArray = goods2.getJSONArray("goodsIds");
        // Integer cuAdId = customerDao.selectCuAdId((Integer)customerId);
        // Integer isInstall = goods2.getInteger("isInstall");
        // Integer couponsId = goods2.getInteger("couponsId");
        // BuluResult buluResult=new BuluResult();
        // //生成订单, 并得到订单号
        // Date beginTime=new Date();
        // Orders order=new Orders();
        // order.setBeginTime(beginTime);
        // order.setCustomerId((int)customerId);
        // order.setCuAdId(cuAdId);
        // order.setIsAZ(isInstall);
        // order.setCouponsId(couponsId);
        // //计算订单的价钱
        // customerDao.insertOrderOfNoIndent(order);
        // //生成商品
        // //删除购物车
        // Map<String,Object> map2=new HashMap<String,Object>();
        // map2.put("orderId",order.getOrderId());
        // Double orderPrice=0.0;
        // for(int i=0;i<goodsIdsArray.size();i++){
        // Integer goodsId=(int)goodsIdsArray.get(i);
        // //通过商品id得到所有的所有样品的价钱
        // Map<String,Object>
        // priceAndCount=customerDao.getSamplePriceAndCountOfFinAccByGoodId(goodsId);
        // Double price=(Double)priceAndCount.get("price");
        // Object saleCount = priceAndCount.get("saleCount");
        // orderPrice+=price*(Double.parseDouble(saleCount.toString()));
        // map2.put("goodsId", goodsId);
        // map2.put("customerId", customerId);
        // // 计算安装费
        // List<Map<String,Object>>
        // list=customerDao.getAccDeatailByGoodsId(goodsId);
        // logger.debug(list);
        // // 生成安装订单,只是没有选择安装时间,那待安装哪里就不显示
        // }
        // Map<String,Object> map=new HashMap<>();
        // if (couponsId!=null) {
        // Coupons couponsDeatil = customerDao.getCouponsDeatil(couponsId);
        // map.put("customerPrice",
        // orderPrice-Double.parseDouble(couponsDeatil.getKnock()+""));
        // }else {
        // map.put("customerPrice", orderPrice);
        // }
        // map.put("orderPrice", orderPrice);
        // //修改订单的价钱
        // map.put("orderId", order.getOrderId());
        // customerDao.updatePriceOfOrders(map);
        // buluResult.setStatus(0);
        // buluResult.setData(order);
        // return buluResult;
        // 这里差一个接口 用户确认订单后付款 改变订单状态和商品属性 改为不是购物车商品
    }

    /**
     * 展示所有收货地址
     */
    public BuluResult showAllAddress(HttpServletRequest request) {
        Integer customerId = getIdFromRedis(request);
        BuluResult buluResult = new BuluResult();
        List<Customer_address> list = customerDao.getAllAddress((int) customerId);
        buluResult.setStatus(0);
        buluResult.setData(list);
        return buluResult;
    }

    /**
     * 新增收货地址
     */
    public BuluResult addNewAddress(HttpServletRequest request, Customer_address customer_address) {
        BuluResult buluResult = new BuluResult();
        Integer customerId = getIdFromRedis(request);
        customer_address.setCustomerId((int) customerId);
        List<Customer_address> list = customerDao.getAllAddress((int) customerId);
        if (null == list) {
            customer_address.setStatus(1);//是否是默认地址  1是 0不是
        } else {
            int flag = 0;
            for (Customer_address address : list) {
                if (address.getStatus() == 1) {
                    flag = 1;
                    break;
                }
            }
            customer_address.setStatus(flag == 0 ? 1 : 0);
        }
        /*
         * if (customer_address.getStatus() == 1) { customerDao.updateStatus();
		 * }
		 */
        customerDao.insertNewAddress(customer_address);
        buluResult.setStatus(0);
        return buluResult;
    }

    /**
     * 更改默认收货地址
     */
    public BuluResult updateDefaultAddress(HttpServletRequest request, Integer cuAdId) {
        Integer customerId = getIdFromRedis(request);
        BuluResult buluResult = new BuluResult();
        customerDao.updateDefaultAddressStatus((int) customerId);//将默认地址更改为当前地址
        customerDao.updateAddressStatus(cuAdId);
        buluResult.setStatus(0);
        return buluResult;
    }

    /**
     * 修改头像
     */
    public BuluResult updateHeadImg(HttpServletRequest request, String headImg) {
        Integer customerId = getIdFromRedis(request);
        BuluResult buluResult = new BuluResult();
        Map<String, Object> map = new HashMap<>();
        map.put("customerId", customerId);
        map.put("headImg", headImg);
        customerDao.updateHeadImg(map);
        buluResult.setStatus(0);
        return buluResult;
    }

    /**
     * 展示优惠卷
     */
    public BuluResult showCoupons(HttpServletRequest request) {
        Integer customerId = getIdFromRedis(request);
        BuluResult buluResult = new BuluResult();
        List<Map<String, Object>> coupons = new ArrayList<>();
        List<Customer_coupons> list = customerDao.getCouponsId((int) customerId);
        for (Customer_coupons couponsId : list) {
            // 通过id查到该优惠卷的详细信息
            Map<String, Object> map = customerDao.getCouponsDeatil2(couponsId.getCouponsId());
            Date date = new Date();
            Date failureTime = (Date) map.get("failureTime");
            if (failureTime.getTime() < date.getTime() && couponsId.getIsUse() == 0) {
                customerDao.updateIsUse((Integer) map.get("couponsId"));
                map.put("isUse", 2);
            } else {
                map.put("isUse", couponsId.getIsUse());
            }
            coupons.add(map);
        }
        if (coupons.size() != 0) {
            buluResult.setStatus(0);
            buluResult.setData(coupons);
        } else {
            buluResult.setStatus(1);
            buluResult.setMessage("暂时没有优惠券!!!");
        }
        return buluResult;
    }

    /**
     * 使用优惠卷
     */
    public BuluResult useCoupons(HttpServletRequest request, Integer couponsId) {
        BuluResult buluResult = new BuluResult();
        Integer customerId = getIdFromRedis(request);
        Map<String, Object> map = new HashMap<>();
        map.put("customerId", customerId);
        map.put("couponsId", couponsId);
        customerDao.updateCouponsStatus(map);
        buluResult.setStatus(0);
        return buluResult;
    }

    /**
     * 设置中的功能:操作指南,关于我们,版本介绍
     */
    public BuluResult setting() {
        // 从数据库中查到 关于我们, 版本介绍
        App app = customerDao.getAppMessage();
        // 从数据库中找到多图软件指导的多图
        List<String> pictures = customerDao.getGuide(app.getAppId());
        Map<String, Object> map = new HashMap<>();
        map.put("about me", app.getAboutMe());
        map.put("version", app.getVersionIntroduce());
        map.put("appGuide", pictures);
        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        buluResult.setData(map);
        return buluResult;
    }

    /**
     * 获取订单明细(订单信息，收货地址信息，图片信息)
     *
     * @param indents
     * @return
     */
    public List<Map<String, Object>> getOrdersData(List<Indent> indents) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        //向商品中添加满减优惠信息
        Double measureMoneyOff = customerDao.selectTerritoryByType(8).getMoney();//满减测量费
        Double deposit = customerDao.selectTerritoryByType(10).getMoney();//押金
        if (indents != null && indents.size() != 0) {
            for (Indent indent : indents) {
                if (indent.getType() == 0 && (indent.getStatus() == 2 || indent.getStatus() == 3||indent.getStatus() ==15||indent.getStatus() ==13||indent.getStatus() ==14)) {//已完成测量单,或者已支付测量单
                    // 查询订单下的商品价格，计算总和到订单价中
                    List<Integer> goodsIdList = customerDao.getGoodIdByIndentId
                            (indent.getIndentId());
                    List<Goods> goodsList = customerDao.getGoodByIndentId(goodsIdList);
                    double customerPrice = 0.0;
                    for (Goods goods : goodsList) {
                        customerPrice = Arith.add(customerPrice,goods.getGoodsPrice());
                        List<Map<String, Object>> acces = getAccessTypeContentOfGoods
                                (goods.getGoodsId());
                        for (Map<String, Object> map2 : acces) {
                            customerPrice = Arith.add(customerPrice,
                                    (map2.get("goodsPrice") != null ?
                                            (double) map2.get("goodsPrice") : 0.0));
                        }

                        indent.setCustomerPrice(customerPrice);
                        Map<String, Object> parameter = new HashMap<String, Object>();
                        parameter.put("indentId", indent.getIndentId());
                        parameter.put("customerPrice", String.valueOf(customerPrice));
                        customerDao.updateIndent(parameter);
                    }

                } else if (indent.getStatus() == 4 && indent.getType() == 1) {//待付款安装单
                    indent.setCustomerPrice(Math.max(indent.getMerchantsPrice
                            (), indent.getIndentPrice()));
                    Map<String, Object> parameter = new HashMap<String, Object>();
                    parameter.put("indentId", indent.getIndentId());
                    parameter.put("customerPrice", String.valueOf(Math.max
                            (indent.getMerchantsPrice(), indent.getIndentPrice())));

                    customerDao.updateIndent(parameter);
                }else if (indent.getStatus() == 4 && indent.getType() == 0){//待付款测量单
                    Map<String, Object> parameter = new HashMap<String, Object>();
                    parameter.put("indentId", indent.getIndentId());
                    parameter.put("customerPrice", indent.getIndentPrice());
                    customerDao.updateIndent(parameter);
                }
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("isExempted",0);//用于判断是否免除过测量费
                if (indent.getType() == 0 && (indent.getStatus() == 2 || indent.getStatus() == 3||indent.getStatus() == 15||indent.getStatus() ==13||indent.getStatus() ==14)){
                    if (indent.getCustomerPrice() >= measureMoneyOff){//满500减免测量费          
                        indent.setCustomerPrice(Arith.sub(Arith.sub(indent.getCustomerPrice(), indent.getIndentPrice()), deposit));
                        map.put("isExempted",1);
                    }else {
                    	System.out.println("customerPrice============"+indent.getCustomerPrice());
                        indent.setCustomerPrice(Arith.sub(indent.getCustomerPrice() , deposit));
                    }
                }else if (indent.getType() == 0 && (indent.getStatus() == 1
                        || indent.getStatus() == 5 || indent.getStatus() == 9 || indent.getStatus() == 4)){
                    indent.setCustomerPrice(Arith.add(indent.getIndentPrice(),deposit));
                }
                if (indent.getCustomerPrice() < 0){
                    indent.setCustomerPrice(0.0);
                }
                Map<String, Object> indentMap = LuKeBeanUtil.fromBeanToMap(indent);
                Map<String, Object> addressMap = LuKeBeanUtil
                        .fromBeanToMap(customerDao.getAddressById(indent.getCuAdId
                                ()));
                List<Map<String, Object>> samples = customerDao.getSampleByIndentId
                        (indent.getIndentId());
                map.putAll(indentMap);// 订单信息
                map.put("addressInfo", addressMap);// 地址信息
                map.put("samples", samples);// 图片地址信息
                list.add(map);
            }
        }
        return list;
    }

    /**
     * g 等待检查
     *
     * @param goodsId
     * @return
     */
    public List<Map<String, Object>> getAcces(Integer goodsId) {
    	
        List<Map<String, Object>> acces = customerDao.getGoods_AccByGoodsId(goodsId);// 得到配件信息
        if (acces == null || acces.size() == 0) {
            acces = new ArrayList<Map<String, Object>>();
            for (Goods_special special : customerDao.selectSpecial(goodsId)) {
                Map<String, Object> accMap = new HashMap<String, Object>();
                accMap.put("goodsId", goodsId);
                accMap.put("specialId", special.getSpecialId());
                accMap.put("whatStructure",special.getWhatStructure());
                accMap.put("sampleImg","");
                accMap.put("sampleId","");
                accMap.put("accessoriesType", special.getAccessoriesType());
                acces.add(accMap);
            }
        }       
        return acces;
    }
    /**
     * 通过indentId得到所有的商品
     */
    public BuluResult getGoodsByIndentId(HttpServletRequest request, Integer indentId) {
        BuluResult buluResult = new BuluResult();
        Indent indent = customerDao.selectIndentInfo(indentId);
        //向商品中添加满减优惠信息
        Double measureMoneyOff = customerDao.selectTerritoryByType(8).getMoney();
        Double deposit = customerDao.selectTerritoryByType(10).getMoney();//押金
        List<Integer> goodsIds = customerDao.getGoodsIdsByIndentId(indentId);
        if (goodsIds.size() <= 0) {
            buluResult.setStatus(1);
            buluResult.setMessage("暂无商品信息");
            return buluResult;
        }
        if (indent.getStatus() == 2) {// 工人完成订单，顾客支付尾款
            // calcPriceByIndentId(indentId, request);
        }
        Double allGoodsPrice = 0.0;
        List<Goods> goods = customerDao.getGoodByIndentId(goodsIds);
        List<Map<String, Object>> list = new ArrayList<>();
        for (Goods goods2 : goods) {
//            if (goods2.getGoodsPrice() == null && goods2.getGoodsPrice() == 0){//工人那边计算价格出错，导致价格没有
//                calcPriceByIndentId(indentId,request);
//            }
            Sample sample = customerDao.getSampleByGoodId(goods2.getGoodsId());
            String location = customerDao.getLocationById(goods2.getLocationId());
            Map<String, Object> map = new HashMap<>();
            Map<String, Object> goodsMap = LuKeBeanUtil.beanToMap(goods2);
            Map<String, Object> sampleMap = LuKeBeanUtil.beanToMap(sample);
            sampleMap.remove("accessoriesTypeId");
            sampleMap.remove("FSProfit");
            if (goodsMap.get("structure") != null){//已完成测量订单显示工人选择的structure
                sampleMap.remove("structure");
            }else {//否则显示sample的structure
                goodsMap.remove("structure");
            }

            map.putAll(goodsMap); // Goods 信息
            map.putAll(sampleMap); // Sample 信息

            List<Map<String, Object>> acces = getAccessTypeContentOfGoods(goods2.getGoodsId());
//			if (indent.getType() == 0 && indent.getStatus() == 2) {
            double accesPrice = 0.0;
            for (Map<String, Object> map2 : acces) {
                if (map2.get("sampleId") != null && !"".equals(map2.get("sampleId"))) {
                    map2.put("sampleImg",
                            customerDao.selectOneSample((Integer) map2.get
                                    ("sampleId")).getSampleImg());
                }
                if ((indent.getType() == 0 && indent.getStatus() == 2) || (indent.getType() == 1)||indent.getStatus()==3) {
                    accesPrice = Arith.add(accesPrice,
                            (map2.get("goodsPrice") != null ? (double) map2.get
                                    ("goodsPrice") : 0.0));
                }
            }
            if ((indent.getType() == 0 && indent.getStatus() == 2) || (indent.getType() == 1)||indent.getStatus()==3) {
                map.put("goodsPrice", Arith.add(goods2.getGoodsPrice(), accesPrice));// 该商品实付金额
            }
//		}
            map.put("acces", acces);// 附属配件信息
            map.put("locationContent", location);// 安装位置
            map.put("indentPrice", indent.getIndentPrice());// 测量费用-安装费用-维修费用

            if (goods2.getAcc() != null && "魔术轨".equals(goods2.getAcc())) {
                map.put("magicRail", Arith.mul(goods2.getSaleNumber(),
                        customerDao.selectMoshugui()));
            }

            allGoodsPrice = Arith.add(allGoodsPrice,map.get("goodsPrice") == null ? 0.0 : (Double) map.get("goodsPrice"));

            list.add(map);
        }
        //主要目的：变更配件或者款式后将总价存入订单
        Map<String,Object> paratemer = new HashMap<>();
        paratemer.put("customerPrice",allGoodsPrice);//所有商品实际价格
        paratemer.put("indentId",indentId);
        
        customerDao.updateIndent(paratemer);        
        indent.setCustomerPrice(allGoodsPrice);
        buluResult.setStatus(0);
        buluResult.setMessage("返回订单详情");
        Map<String,Object> map = new HashMap<>();
        map.put("goods",list);
        Double tempCustomerPrice = -0.01;
        //判断需要支付的是什么费用
        map.put("isExempted",0);//用于判断是否免除过测量费
        if (indent.getType() == 0 && (indent.getStatus() == 4 || indent.getStatus() == 9
                ||indent.getStatus() == 1 ||indent.getStatus() == 5)){//定金
            tempCustomerPrice = Arith.add(indent.getIndentPrice(), deposit);
        } else if (indent.getType() == 0 && indent.getStatus() == 2){//全款
            if (indent.getCustomerPrice() >= measureMoneyOff){//满500减免测量费
                tempCustomerPrice = Arith.sub(Arith.sub(allGoodsPrice, indent.getIndentPrice()), deposit);
                map.put("isExempted",1);
            }else {
                tempCustomerPrice = Arith.sub(allGoodsPrice, deposit);
            }
        } else if (indent.getType() == 4 && indent.getStatus() == 4){//或纯配件订单
            tempCustomerPrice = indent.getCustomerPrice();
        } else if (indent.getType() == 1 && indent.getStatus() == 4){//安装费
            tempCustomerPrice = indent.getIndentPrice();
        }
        map.put("customerPrice",tempCustomerPrice < 0 ? 0.0 : tempCustomerPrice);//应付实际金额
        buluResult.setData(map);
        return buluResult;
    }

    /**
     * 取消订单：1、已付定金-工人测量{1完成：再次购买为尾款，状态不变；2未完成：工人接单后取消定金不退，状态改
     * 为待付定金}
     * 2、已付尾款-制作之前取消，退尾款，不退定金，状态改为待付尾款；制作中尾款不退，再次购买，状态改为待付尾款
     * 3、已付安装费-工人安装{1完成：不可取消；2未完成：工人接单后取消安装费不退，取消后状态改为待付安装费}
     */
    public BuluResult updateIndentByIndentId(HttpServletRequest request, Integer indentId) {
        Indent indent = customerDao.selectIndentInfo(indentId);
        Customer customer = customerDao.getCustomerById(getIdFromRedis(request));
        Double customerPrice = indent.getCustomerPrice();
        Double wallet = customer.getWallet();
        Double returnMoney = 0.0;
        //向商品中添加满减优惠信息
        Double measureMoneyOff = customerDao.selectTerritoryByType(8).getMoney();
        Double deposit = customerDao.selectTerritoryByType(10).getMoney();//押金
        Double indentPrice=indent.getIndentPrice()==null?0.0:indent.getIndentPrice();
//        if (indent.getCustomerPrice() >= measureMoneyOff){//满500减免测量费
            returnMoney = Arith.sub(Arith.sub(indent.getCustomerPrice() , indentPrice),deposit);
//        }else {
//            returnMoney = indent.getCustomerPrice();
//        }

        int status = indent.getStatus();
        int type = indent.getType();
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> info = new HashMap<>();
        if (type == 0) {// 测量单
            switch (status) {
                // 工人接单但还未完成，取消后仍需再次支付测量费再次测量
                case 9:// 待接单
                    info.put("wallet", Arith.add(wallet,customerPrice));
                    break;
                case 3:// 已付尾款
                    info.put("wallet", Arith.add(wallet,returnMoney));
                    map.put("status", 2);
                    break;
                case 2:// 已测量完成
                    info.put("wallet", Arith.add(wallet,returnMoney));
                    map.put("status", 2);
                    break;
                case 1:// 已接单
                case 5:// 已出发
                    map.put("status", 4);
                    Map<String,Object> map2 = new HashMap<>();
                    map2.put("acceptTime", "666");
                    map2.put("workerId", "666");
                    indentDao.updateIndent(map2);
                    break;
                case 13:// 制作中
                case 14:// 已发货
                    map.put("status", 2);
                    break;
                default:
                    break;
            }
        } else if (type == 1) {// 安装单
            switch (status) {
                // 工人接单但还未完成，取消后仍需再次支付安装费费再次安装
                case 9:// 待接单
                    info.put("wallet", Arith.add(wallet,customerPrice));
                    map.put("status", 4);
                    break;
                case 1:// 已接单
                case 5:// 已出发
                    map.put("status", 4);
                    Map<String,Object> map2 = new HashMap<>();
                    map2.put("acceptTime", "666");
                    map2.put("workerId", "666");
                    indentDao.updateIndent(map2);
                    break;
                default:
                    break;
            }
        } else if (type == 4) {// 纯配件订单
            switch (status) {
                case 3:// 已付尾款
                    info.put("wallet", Arith.add(wallet,customerPrice));
                    map.put("status", 4);
                    break;
                case 13:// 制作中
                case 14:// 已发货
                    map.put("status", 2);
                    break;
                default:
                    break;
            }

        }
        map.put("indentId", indentId);
        map.put("isDelete", 1);
        customerDao.updateIndentByIndentId(map);

        info.put("customerId", getIdFromRedis(request));
        customerDao.updateUserInfo(info);

        // 取消订单的相对应的扣款操作（未做）
        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        return buluResult;
    }

    /**
     * 功能：返回已完成订单
     */
    public BuluResult clickOver(HttpServletRequest request) {
        BuluResult buluResult = new BuluResult();
        Integer customerId = getIdFromRedis(request);
        Integer page = request.getParameter("page") == null ? 0
                : (Integer.parseInt(request.getParameter("page")) * 10 - 10);
        Map<String, Object> inParames = new HashMap<String, Object>();
        List<Integer> status = new ArrayList<Integer>();
        // status.add(11);// 完成
        status.add(15);// 家居订单完成，不同于工人订单完成，因为工人完成时家居还并未结束
        inParames.put("status", status);
        inParames.put("customerId", customerId);
        inParames.put("isDelete", 0);
        inParames.put("page",page);
        List<Indent> indents = customerDao.getCompletedIndents(inParames);
        // 返回订单数据
        List<Map<String, Object>> list = getOrdersData(indents);

        if (list == null || list.size() == 0){
            buluResult.setStatus(1);
            buluResult.setData(list);
        }else {
            buluResult.setStatus(0);
            buluResult.setData(list);
        }
        return buluResult;
    }

    /**
     * 功能：返回已取消订单
     */
    public BuluResult clickCancel(HttpServletRequest request) {
        BuluResult buluResult = new BuluResult();
        Map<String, Object> inParames = new HashMap<String, Object>();
        Integer customerId = getIdFromRedis(request);
        inParames.put("customerId", customerId);
        inParames.put("isDelete", 1);
        List<Indent> indents = customerDao.getDiffrStatusIndents(inParames);
        // 返回所有已取消indent数据
        Map<String, Object> map = new HashMap<String, Object>();
        List<Map<String, Object>> indentsList = getOrdersData(indents);
        map.put("indent", indentsList);
        buluResult.setStatus(0);
        buluResult.setData(map);
        buluResult.setMessage("已返回取消订单");
        return buluResult;
    }

    /**
     * 功能：返回待安装订单
     */
    public BuluResult clickNoInstall(HttpServletRequest request) {
        BuluResult buluResult = new BuluResult();
        Map<String, Object> inParames = new HashMap<String, Object>();
        Integer customerId = getIdFromRedis(request);
        List<Integer> type1 = new ArrayList<Integer>();
        type1.add(1);// 安装单
        List<Integer> status = new ArrayList<Integer>();
        status.add(9);// 待结单
        status.add(1);// 已接单
        status.add(5);// 已出发
        inParames.put("customerId", customerId);
        inParames.put("type1", type1);
        inParames.put("status", status);
        inParames.put("isDelete", String.valueOf(0));
        List<Indent> indents = customerDao.getDiffrStatusIndents(inParames);
        // 返回订单数据
        List<Map<String, Object>> list = getOrdersData(indents);
        buluResult.setStatus(0);
        buluResult.setData(list);
        return buluResult;
    }

    /**
     * 功能：返回已付款订单
     */
    public BuluResult clickAlreadyPay(HttpServletRequest request) {
        BuluResult buluResult = new BuluResult();
        Integer customerId = getIdFromRedis(request);
        List<Integer> status = new ArrayList<Integer>();
        status.add(3);// 已付款但为开始制作
        status.add(13);// 商品制作中
        status.add(14);// 已发货
        Map<String, Object> inParames = new HashMap<String, Object>();
        inParames.put("customerId", customerId);
        inParames.put("status", status);
        inParames.put("isDelete", String.valueOf(0));
        // 进行中的订单都是测量安装维修的订单
        List<Indent> indents = customerDao.getDiffrStatusIndents(inParames);
        // 返回订单数据
        List<Map<String, Object>> list = getOrdersData(indents);
        buluResult.setStatus(0);
        buluResult.setData(list);
        buluResult.setMessage("返回已支付订单");
        return buluResult;
    }

    /**
     * 功能：返回 待测量订单
     */
    public BuluResult clickGoing(HttpServletRequest request, int types) {
        BuluResult buluResult = new BuluResult();
        Integer customerId = getIdFromRedis(request);
        List<Indent> indents = null;
        if (types == 0) {
            List<Integer> type1 = new ArrayList<Integer>();// 测量单
            List<Integer> status = new ArrayList<Integer>();
            Map<String, Object> inParames = new HashMap<String, Object>();
            // 待测量
            type1.add(0);

            status.add(1);// 已接单
            status.add(5);// 已出发
            status.add(9);// 待结单

            inParames.put("status", status);
            inParames.put("customerId", customerId);
            inParames.put("type1", type1);
            inParames.put("isDelete", String.valueOf(0));

            indents = customerDao.getDiffrStatusIndents(inParames);
        } else {
            // 待支付
            indents = customerDao.getPayedIndents(customerId);
        }
        // 返回订单数据
        List<Map<String, Object>> list = getOrdersData(indents);
        buluResult.setStatus(0);
        buluResult.setData(list);
        return buluResult;
    }

    // 已取消改成重新购买
    public BuluResult reBuyIndent(HttpServletRequest request, Integer indentId) {
        Map<String, Object> map = new HashMap<>();
        map.put("indentId", indentId);
        map.put("isDelete", 0);
        // 这里没写完
        customerDao.updateIndentByIndentId(map);
        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        return buluResult;
    }

    // 重选款式 //{oldGoodsId:,sampleId:}
    public BuluResult updateGoodOfIndent(HttpServletRequest request, String goodsId, String sampleId) {
        // 把goodsId中的sampleId修改
        Map<String, Object> map = new HashMap<>();
        map.put("goodsId", goodsId);
        map.put("sampleId", sampleId);
        customerDao.updateGoodByGoodId(map);
        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        return buluResult;
    }

    /**
     * 购物车中商品添加配件 //goodsIds:{goodsId:,goods:{},accessoriesTypeId: }
     * 业务逻辑：此时添加配件是已经完成测量的订单，工人那边已经添加了这些配件的goods和goods_special,这里只需要
     * 更新已有即可
     */
    public BuluResult addGoodsOfAcc(HttpServletRequest request, Integer sampleId, Integer indentId,
                                    Integer goodsId,
                                    Integer accId, Integer whatStructure) {
        // 一、根据accId更新goods和goods_special
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("goodsId", accId);
        map.put("sampleId", sampleId);
        map.put("type", 2);// 0布艺帘 1成品帘2配件
        // 计算变更后配件价格
        Double goodsPrice = 0.0;
        Goods goods = customerDao.selectGoodsByGoodsId(accId);
        Double price = customerDao.selectPPrice(sampleId); // 根据产品号查询配件价格
        if ("直轨".equals(goods.getAccessoriesType()) || "弯轨".equals(goods.getAccessoriesType())) {//直轨// 弯轨
                    goodsPrice = price * goods.getNumber() * goods.getSaleNumber();
            if (goods.getAcc().contains("魔术轨")) {// 代表包含魔术轨 则需再加一个商品 魔术轨
                goodsPrice += goods.getSaleNumber() * customerDao.selectMoshugui();
                goods.setAddpeijian(1);//// 1加装了魔术轨 0没有加装魔术轨
            }
        } else if ("罗马杆".equals(goods.getAccessoriesType()) || "魔术轨".equals
                (goods.getAccessoriesType())) {// 罗马杆
            // 魔术轨
            goodsPrice = price * goods.getNumber() * goods.getSaleNumber();
        } else if ("壁钩".equals(goods.getAccessoriesType()) || "挂绳".equals(goods.getAccessoriesType
                ())) {// 璧钩
            // 挂绳
            goodsPrice = price * goods.getNumber();
        }
        map.put("goodsPrice", goodsPrice);
        customerDao.updateGoods(map);
        // calcPriceByIndentId(indentId, request);

        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        return buluResult;
    }

    // 点击查询待评价
    // public BuluResult NoEvaluation(HttpServletRequest request) {
    // BuluResult buluResult = new BuluResult();
    // Map<String, Object> inParames = new HashMap<String, Object>();
    // Integer customerId = getIdFromRedis(request);
    //
    // List<Integer> status = new ArrayList<Integer>();
    // status.add(11);// 待评价
    //
    // inParames.put("customerId", customerId);
    // inParames.put("status", status);
    // inParames.put("isDelete", String.valueOf(0));
    //
    // List<Map<String, Object>> list =
    // getOrdersData(customerDao.getDiffrStatusIndents(inParames));
    // buluResult.setStatus(0);
    // buluResult.setMessage("已返回待评价订单");
    // buluResult.setData(list);
    // return buluResult;
    // }

    private void calcPriceByIndentId(Integer indentId, HttpServletRequest request) {
        // TODO Auto-generated method stub
        List<Goods> goodss = customerDao.getGoodByIndentId(customerDao.getGoodIdByIndentId(indentId));

        // 获取订单下的所有商品，计算价格，并存入goods中
        for (Goods goods : goodss) {
            if (goods.getType() != 2) {
                Map<String, Object> map2 = new HashMap<>();
                map2.put("goodsId", goods.getGoodsId());
                map2.put("customerId", getIdFromRedis(request));
                Map<String, Object> update = new HashMap<>();
                Goods goodsList;
                Map<String, Object> finishList;
                Goods price;
                Object curtainPrice;
                Map<String, Object> parameter = new HashMap<>();
                if (goods.getType() == 1) {// 成品帘
                    // {"sampleId":1002,"finish":[{"wide":"2","high":"2"}]}
                    finishList = customerDao.getGoodsToCaclCurtainPriceByGoodsId
                            (goods.getGoodsId());

                    parameter.put("sampleId", finishList.get("sampleId"));
                    ArrayList<Map<String, Object>> list = new ArrayList<>();
                    Map<String, Object> childParameter = new HashMap<>();
                    childParameter.put("wide", finishList.get("wide"));
                    childParameter.put("high", finishList.get("high"));
                    list.add(childParameter);
                    parameter.put("finish", list);
                    curtainPrice = priceService.getPriceOfFinish(new Gson().toJson
                            (parameter)).getData();

                    update.put("goodsId", goods.getGoodsId());
                    update.put("goodsPrice", curtainPrice);
                } else if (goods.getType() == 0) {// 布艺帘
                    goodsList = customerDao.getGoodsToCaclPriceByGoodsId(map2);
                    price = (Goods) priceService.calcCurtainPrice(goodsList).getData();
                    Double sumPrice = price.getGoodsPrice();
                    Double sumBPrice = price.getSumBPrice();
                    Double sumShadingBprice = price.getSumShadingBprice();
                    Double sumSPrice = price.getSumSPrice();
                    Double sumLPrice = price.getSumLPrice();                   
                    update.put("goodsId", goods.getGoodsId());
                    update.put("goodsPrice", sumPrice);
                    update.put("sumBPrice", sumBPrice);
                    update.put("sumShadingBprice", sumShadingBprice);
                    update.put("sumSPrice", sumSPrice);
                    update.put("sumLPrice", sumLPrice);
                }
                customerDao.updateGoodByGoodId(update);       
            }
        }
    }

    // 在 待评价页面点击某个订单
    public BuluResult GoEvaluation(Integer indentId) {
        List<Map<String, Object>> list2 = customerDao.getSampleDetailByOrderId(indentId);
        for (int a = 0; a < list2.size(); a++) {
            list2.get(a).put("acces", this.getAcces((Integer) list2.get(a).get("goodsId")));
            // 0没有 1测量 2安装 3测量+安装
            if (customerDao.selectCWorker(indentId) != null && customerDao.selectAWorker(indentId)
                    != null) {
                list2.get(a).put("gongrenType", 3);//工人类型==》测量+安装
                if ((Integer) customerDao.selectCWorker(indentId).get("isEva") != 1
                        && (Integer) customerDao.selectAWorker(indentId).get("isEva")
                        != 1) {
                    list2.get(a).put("isEvaWorker", 0);
                } else {
                    list2.get(a).put("isEvaWorker", 1);
                }
            } else if (customerDao.selectCWorker(indentId) != null && customerDao.selectAWorker
                    (indentId) == null) {
                list2.get(a).put("gongrenType", 1);
                if ((Integer) customerDao.selectCWorker(indentId).get("isEva") != 1) {
                    list2.get(a).put("isEvaWorker", 0);
                } else {
                    list2.get(a).put("isEvaWorker", 1);
                }
            } else if (customerDao.selectCWorker(indentId) == null && customerDao.selectAWorker
                    (indentId) != null) {
                list2.get(a).put("gongrenType", 2);
                if ((Integer) customerDao.selectAWorker(indentId).get("isEva") != 1) {
                    list2.get(a).put("isEvaWorker", 0);
                } else {
                    list2.get(a).put("isEvaWorker", 1);
                }
            } else {
                list2.get(a).put("gongrenType", 0);
                list2.get(a).put("isEvaWorker", 1);
            }
            list2.get(a).put("CWorker", customerDao.selectCWorker(indentId));
            list2.get(a).put("AWorker", customerDao.selectAWorker(indentId));
        }
        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        buluResult.setData(list2);
        return buluResult;
    }

    /**
     * 删除该商品的一个配件
     */
    public BuluResult deleteAccOfGoodOfIndent(HttpServletRequest request, Integer goodsId, Integer accId) {
        customerDao.deleteGoodOfGoodId(accId);
        Goods_accses goods_accses = new Goods_accses();
        goods_accses.setGoodsId(goodsId);
        goods_accses.setAccId(accId);
        customerDao.deleteGoods_accByGoodIdAndAccId(goods_accses);
        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        return buluResult;
    }

    /**
     * 通过订单号得到所有商品的详情
     */
    public BuluResult getGoodsByOrderId(Integer indentId) {
        List<Map<String, Object>> list = customerDao.getSampleDetailByOrderId(indentId);
        for (int a = 0; a < list.size(); a++) {
            Integer goodsId = (Integer) (list.get(a).get("goodsId"));
            list.get(a).put("acces", this.getAcces(goodsId));
        }
        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        buluResult.setData(list);
        return buluResult;
    }

    /**
     * 功能：客户取消订单（测量单，安装单）
     *
     * @param request
     * @param indentId
     * @return
     */
    @Transactional
    public BuluResult cancelIndent(HttpServletRequest request, Integer indentId, Integer type) {
        BuluResult buluResult = new BuluResult();
        Indent inparame = new Indent();
        inparame.setIndentId(indentId);
        Indent indent = customerDao.selectIndent(inparame);// 订单
        if (indent == null) {
            buluResult.setData(1);
            buluResult.setMessage("查无此单,请确认你的订单号");
            return buluResult;
        }
        Customer customer = customerDao.getCustomerById(getIdFromRedis(request));// 顾客
        Integer status = indent.getStatus();// 当前订单状态
        // 退款
        if (status == 4) {// 未支付
            buluResult = updateIndentByIndentId(request, indentId);// 首先取消订单
            buluResult.setMessage(buluResult.getStatus() == 0 ? "取消订单成功" : "操作失败,请稍后重试");
            return buluResult;
        } else {// 已支付
            if (status == 13 | status == 14) {
                buluResult.setData(1);
                buluResult.setMessage("暂不能取消订单");
                return buluResult;
            }
            buluResult = updateIndentByIndentId(request, indentId);// 首先取消订单
            if (buluResult.getStatus() == 0) {
                // 准备返回给工人的钱
                double toworker = 0.00;
                // 准备返回给顾客的钱
                double wallet = 0.00;
                // 扣款金额
                double subMoney = 0.0;
                Map<String, Double> punishMap = customerDao.selectRules(indentId);
                // 测量单-取定金（测量费+押金） 安装单-安装费
                Double fee = indent.getType() == 0 ? customerDao.selectTerritoryByType(10).getMoney()
                        : (indent.getType() == 1 ? indent.getIndentPrice() : 0);
                switch (status) {
                    // case 0: // 已付款： 未完成 --全额退还给顾客
                    case 1: // 已接单 --减去20
                        if (punishMap == null || punishMap.size() == 0) {
                            buluResult.setStatus(1);
                            return buluResult;
                        }
                        subMoney = punishMap.get("punishWorker");
                        wallet = Arith.sub(fee, subMoney);
                        toworker = punishMap.get("punishWorker");// 补给工人对的钱
                        break;
                    case 3: // 已付款 : 还未制作/发货
                        wallet = indent.getCustomerPrice();
                        break;
                    case 5: // 已出发 --减去50
                        if (punishMap == null || punishMap.size() == 0) {
                            buluResult.setStatus(1);
                            return buluResult;
                        }
                        subMoney = punishMap.get("punishClient");
                        wallet = Arith.sub(fee, subMoney);
                        toworker = punishMap.get("punishClient");
                        break;
                    case 9: // 已付款 ： 待接单 --全额退还给顾客
                        wallet = fee;
                        break;
                    default:// 2已完成测量-安装,取消不予退款
                        break;
                }
                // 更新顾客钱包
                if (wallet != 0.00) {
                    if (customer == null) {
                        buluResult.setData(1);
                        buluResult.setMessage("查无该顾客");
                        return buluResult;
                    }
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("wallet", wallet + (customer.getWallet()));
                    map.put("customerId", customer.getCustomerId());
                    customerDao.updateCustomerWallet(map);
                    // 做交易记录---暂时没有
                    CustomerWalletRecord customerWalletRecord = new CustomerWalletRecord
                            ();
                    customerWalletRecord.setCustomerId(customer.getCustomerId());
                    customerWalletRecord.setIndentId(indentId);
                    customerWalletRecord.setSubMoney(subMoney);// 因取消订单扣款金额
                    customerWalletRecord.setFinalLostMoney(subMoney);
                    customerWalletRecord.setFinalGetMoney(wallet);
                    customerWalletRecord.setType(type);// '行为交易种类1:定金，2:安装费，3:尾款，4:充值, 5:提现6:全配件支付, ',
                    customerWalletRecord.setRecordBeginTime(DateUtils.getDateTime());
                    customerWalletRecord.setRecordEndTime(DateUtils.getDateTime());
                    customerWalletRecord.setStatus(1);// 成功
                    customerWalletRecord.setMethod("钱包余额变动");
                    customerWalletRecord.setOrderNo(LuKeOrderNoUtil.getCustomerOrderNo
                            (indentId,
                                    PayMethod.OTHERPAY.getIndex(),
                                    TypeOfIndent.CANCEL.getIndex()));
                    customerWalletRecord.setRemark("商家或者个人取消订单的违约罚款");

                    customerWalletRecordService.insertCustomerWalletRecord
                            (customerWalletRecord);
                }
                // 更新工人钱包
                if (toworker != 0.00) {
                    Worker worker = workerDao.selectWorker(indent.getWorkerId());
                    if (worker == null) {
                        buluResult.setData(1);
                        buluResult.setMessage("查无该工人");
                        return buluResult;
                    }
                    Map<String, Object> send = new HashMap<String, Object>();
                    send.put("workerId", worker.getWorkerId());
                    send.put("wallet", worker.getWallet() + toworker);
                    // 更新工人钱包
                    workerDao.updateWalletComple(send);
                    // 做交易记录
                    workerWalletRecordService.insertWorkerWalletRecord(worker.getWorkerId
                                    (), indentId, 2, toworker,
                            null, null, toworker, null, null, null,
                            WorkerType.MERCHANTS_CANCLE.getIndex(), 1,
                            "商家或者个人取消订单工人获取规定罚款", 0, "钱包余额变动");
                }
            } else {
                buluResult.setStatus(1);
                buluResult.setMessage("订单取消失败");
                return buluResult;
            }
        }
        buluResult.setStatus(0);
        buluResult.setMessage("订单取消成功");
        return buluResult;
    }

    /**
     * 功能： 已付款中取消订单
     */
    public BuluResult cancelOrders(HttpServletRequest request, Integer orderId) {
        BuluResult buluResult = new BuluResult();
        // 从数据库中得到这个订单是否已经被审核
        int status = customerDao.getIsAuditingByOrderId(orderId);
        if (status == 0 || status == 1 || status == 2) {
            Map<String, Object> map = new HashMap<>();
            map.put("orderId", orderId);
            map.put("isDelete", 1);
            customerDao.updateStatusOfOrders(map);
            buluResult.setMessage("该订单已取消!");
            buluResult.setStatus(0);
        } else {
            // 不能取消
            buluResult.setStatus(1);
            buluResult.setMessage("该订单已被审核不能取消!");
        }
        return buluResult;
    }

    public BuluResult indentToOrders(HttpServletRequest request, String good) {
        Integer customerId = getIdFromRedis(request);
        JSONObject parseObject = JSONObject.parseObject(good);
        Object goods = parseObject.get("goods");
        Object cuAdId = parseObject.get("cuAdId");
        Object countPrice = parseObject.get("countPrice");
        // 如果 isAZ==0,则是不需要安装的
        Object isAZ = parseObject.get("isAZ");
        Orders orders = new Orders();
        Date date = new Date();
        orders.setBeginTime(date);
        orders.setCuAdId((int) cuAdId);
        orders.setOrderPrice(Double.parseDouble(countPrice.toString()));
        orders.setCustomerId((int) customerId);
        orders.setIsAZ((int) isAZ);
        customerDao.indentToOrders(orders);
        // 生成安装订单
        // 这个地方要生成测量费
        Indent indent = new Indent();
        indent.setBeginTime(date);
        Customer_address address = customerDao.selectAddress((Integer) cuAdId);
        address.setStatus(null);
        customerDao.insertNewAddress(address);
        indent.setCuAdId(address.getCuAdId());// '地址ID',
        indent.setIndentPrice(parseObject.getDouble("indentPrice"));
        indent.setCustomerId((int) customerId);
        indent.setType(0);
        indent.setOrderId(String.valueOf(orders.getOrderId()));
        customerDao.insertIndentOfInsatll2(indent);
        JSONArray goodsArray = JSONArray.parseArray(goods.toString());
        for (int i = 0; i < goodsArray.size(); i++) {
            // 这是一个商品
            JSONObject good2 = JSONObject.parseObject(goodsArray.get(i).toString());
            Object goodsId = good2.get("goodsId");
            Map<String, Object> map = new HashMap<>();
            map.put("goodsId", goodsId);
            map.put("orderId", orders.getOrderId());
            map.put("customerId", customerId);
            customerDao.updateGoodByIdAddOrder(map);
            Map<String, Object> map2 = new HashMap<>();
            map2.put("goodsId", goodsId);
            map2.put("indentId", indent.getIndentId());
            customerDao.insertGood_Indent(map2);
            // 把选择的商品isUse标记成已经购买, 没勾选的标记没勾选
            Map<String, Object> map3 = new HashMap<>();
            map3.put("goodsId", goodsId);
            map3.put("isUse", good2.get("isUse"));
            customerDao.updateGoodByIsUse(map3);
        }
        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        return buluResult;
    }

    /**
     * 功能：已付款的确认收货--布艺帘订单 {indentId:4433,subscribeTime:,city:isAZ:0}
     */
    @Transactional
    public BuluResult confirmReceipt(HttpServletRequest request, String parame) {
        JSONObject jsonObject = JSONObject.parseObject(parame);
        BuluResult buluResult = new BuluResult();
        if (jsonObject == null) {
            buluResult.setStatus(1);
            buluResult.setMessage("参数解析有误");
            return buluResult;
        }
        Integer indentId = jsonObject.getInteger("indentId");
        Integer isAZ = jsonObject.getInteger("isAZ");
        if (indentId == null || isAZ == null) {
            buluResult.setData(1);
            buluResult.setMessage("参数不能为空");
            return buluResult;
        }
        // 更新订单为已完成
        Indent indent = new Indent();
        indent.setStatus(15); // 已完成
        indent.setIndentId(indentId);
        // 需 安装的，生成安装单
        if (isAZ == 1) {
            buluResult = this.insertAzhuang(request, parame);
            if (buluResult.getStatus() == 0) {
                // 3.2:更新测量单信息
                indent.setIsInstalled(1);// 已申请安装
                buluResult.setStatus(0);
                buluResult.setMessage("已确认收货");
            } else {
                buluResult.setStatus(1);
                buluResult.setMessage("安装单生成失败");
            }
        }
        customerDao.updateMeterIndent(indent);
        return buluResult;
    }

    // 生成待安装订单
    public BuluResult insertInstallIndent(HttpServletRequest request, Integer orderId, Date date,
                                          Integer cuAdId,Integer isAZ) {
        List<Map<String, Object>> goods = customerDao.getGoodsByOrderId(orderId);
        // 生成indent
        if (isAZ == 0) {// 安装
            Indent indent = new Indent();
            indent.setSubscribeTime(date);// 预约时间
            indent.setBeginTime(new Date());// 下单时间
            indent.setType(1);// 安装单
            indent.setOrderId(String.valueOf(orderId));
            indent.setIndentSource(2);
            Customer_address address = customerDao.selectAddress(cuAdId);
            address.setStatus(null);
            customerDao.insertNewAddress(address);
            indent.setCuAdId(address.getCuAdId());// '地址ID',
            indent.setCustomerId((int) (request.getSession().getAttribute("customerId")));// 顾客ID
            customerDao.insertIndentOfInsatll2(indent);
            for (Map<String, Object> map : goods) {
                Map<String, Object> map2 = new HashMap<>();
                map2.put("goodsId", map.get("goodsId"));
                map2.put("indentId", indent.getIndentId());
                customerDao.insertGood_Indent(map2);
            }
        } else if (isAZ == 1) {// 不安装
            Indent indent = new Indent();
            indent.setSubscribeTime(date);
            indent.setOrderId(String.valueOf(orderId));
            customerDao.updateIndentOfInstall(indent);// 修改预约时间
        }
        BuluResult buluResult = new BuluResult();
        buluResult.setMessage("安装单生成成功");
        buluResult.setStatus(0);
        return buluResult;
    }

    // 评价
    public BuluResult submitEvaluation(HttpServletRequest request, Evaluation evaluation, String imgs,
                                       String goodsId) {
        BuluResult buluResult = new BuluResult();
        if (evaluation != null) {
            evaluation.setCustomerId(this.getIdFromRedis(request));
            // 1添加评价
            evaluation.setEvaTime(new Date());
            int rows = customerDao.insertGEvaluation(evaluation);
            if (rows != 1) {
                buluResult.setStatus(1);
                buluResult.setMessage("评价失败");
                return buluResult;
            }
            // 2.修改订单下商品为已评价
            if (goodsId != null && !("".equals(goodsId))) {
                Goods goods = new Goods();
                goods.setGoodsId(Integer.parseInt(goodsId));
                goods.setIsEvaluation(1);
                goodsDao.updateGoods(goods);
            }
            // 3添加评价图片
            if (imgs != null && !("".equals(imgs))) {
                JSONArray imgArray = JSONArray.parseArray(imgs);
                for (int i = 0; i < imgArray.size(); i++) {
                    Map<String, Object> imgMap = new HashMap<String, Object>();
                    Integer evaluationId = evaluation.getEvaluationId();
                    imgMap.put("img", imgArray.get(i));
                    imgMap.put("evaluationId", evaluationId);
                    customerDao.insertGPicture(imgMap);
                }
            }
            buluResult.setStatus(0);
            buluResult.setMessage("已提交评价");
        } else {
            buluResult.setStatus(1);
            buluResult.setMessage("无评价内容");
        }
        return buluResult;
    }

    // 全是配件的orders,用户使用了优惠卷,账单减去这个价钱
    public BuluResult updateOrderPriceByUseCoupons(HttpServletRequest request, Integer orderId, Integer
            couponsId) {
        Map<String, Object> map = new HashMap<>();
        map.put("customerId", request.getSession().getAttribute("customerId"));
        map.put("orderId", orderId);
        map.put("couponsId", couponsId);
        customerDao.updateOrderByCoupons(map);
        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        return buluResult;
    }

    // 进行中付测量费
    public BuluResult payMeasureMoney(HttpServletRequest request, Integer indentId) {
        return null;
    }

    // 查询顾客信息
    public BuluResult selectCustomerX(HttpServletRequest request) {
        Integer customerId = getIdFromRedis(request);
        Map<String, Object> map = new HashMap<>();
        map.put("customerId", customerId);
        Customer customer = customerDao.selectMessage(map);
        Map<String,Object> customer2 = LuKeBeanUtil.fromBeanToMap(customer);
        customer2.remove("weiyi");
        customer2.remove("password");
        List<Integer> list = new ArrayList<>();
        list.addAll(customerDao.selectCollectionDL((Integer) customer2.get("customerId")));
        customer2.put("shoucang", list);
        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        buluResult.setData(customer2);
        return buluResult;
    }

    // 删除地址
    public BuluResult deleteAddress(HttpServletRequest request, Integer cuAdId) {
        Integer customerId = getIdFromRedis(request);
        customerDao.deleteAddress(cuAdId, customerId);
        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        return buluResult;
    }

    // 待安装中点击安装完成
    public BuluResult installComplete(Integer indentId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("indentId", indentId);
        map.put("finishTime", new Date());
        customerDao.installComplete(map);
        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        return buluResult;
    }

    // 修改地址接口
    public BuluResult chageAddress(Customer_address customer_address) {
        customerDao.chageAddress(customer_address);
        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        return buluResult;
    }

    // 进入我的页面
    public BuluResult Mypage(HttpServletRequest request) {
        // 我的ID
        Integer customerId = getIdFromRedis(request);
        // 得到进行中角标
        Integer ongoingN = customerDao.ongoingJiaoB(customerId);
        // 待付款角标
        Integer payingIn = customerDao.selectPayingB(customerId);
        // 得到已付款角标
        Integer paymentN = customerDao.YesPayment(customerId);
        // 得到待安装角标
        Integer installN = customerDao.stayInstall(customerId);
        // 已取消角标
        Integer cancelN = customerDao.cancelJiaoB(customerId);
        // 得到已完成角标
        Integer completeN = customerDao.completeJiaoB(customerId);
        // 得到待评价角标
        Integer evaluateN = 0;
        // 查询用户默认地址
        Map<String, Object> defaultAddress = customerDao.selectDefault(customerId);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("ongoingN", ongoingN);
        map.put("paymentN", paymentN);
        map.put("installN", installN);
        map.put("evaluateN", evaluateN);
        map.put("completeN", completeN);
        map.put("cancelN", cancelN);
        map.put("payingIn", payingIn);
        map.put("defaultAddress", defaultAddress);
        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        buluResult.setData(map);
        return buluResult;
    }

    // 顾客申请售后
    public BuluResult insertAfterSales(HttpServletRequest request, Integer goodsId, String problem, String
            imgs) {
        Integer customerId = getIdFromRedis(request);
        Goods_afterSales goods_afterSales = new Goods_afterSales();
        goods_afterSales.setCustomerId(customerId);
        goods_afterSales.setGoodsId(goodsId);
        goods_afterSales.setProblem(problem);
        customerDao.insertAfterSales(goods_afterSales);// 添加售后
        customerDao.updateApplyAfter(goodsId);//修改商品为已申请售后
        Map<String, Object> afterMap = new HashMap<String, Object>();
        afterMap.put("disposeTime", new Date());
        afterMap.put("goodsId", goodsId);
        afterMap.put("disposeId", 1);
        customerDao.insertAfterFlow(afterMap);
        if (imgs != null) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("afterSalesId", goods_afterSales.getAfterSalesId());
            JSONArray jsonArray = JSONArray.parseArray(imgs);
            for (int a = 0; a < jsonArray.size(); a++) {
                String img = (String) jsonArray.get(a);
                map.put("img", img);
                customerDao.insertAfterImg(map);
            }
        }
        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        return buluResult;
    }

    // (申请售后的商品才能点击)查看商品售后
    public BuluResult selectAfterSales(Integer goodsId) {
        List<Map<String, Object>> list = customerDao.selectAfterFlow(goodsId);
        for (int a = 0; a < list.size(); a++) {
            Integer disposeId = (Integer) list.get(a).get("disposeId");
            list.get(a).put("disposeString", customerDao.selectDispose(disposeId));
        }
        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        buluResult.setData(list);
        return buluResult;
    }

    // 搜索配件
    public BuluResult selectPeijian(Integer accessoriesTypeId, Integer page) {
        Map<String, Object> map = new HashMap<>();
        map.put("page", (page - 1) * 10);
        map.put("accessoriesTypeId", accessoriesTypeId);
        List<Sample> list = customerDao.selectPeijian(map);
        BuluResult buluResult = new BuluResult();
        if (list != null && list.size() > 0) {
            buluResult.setStatus(0);
            buluResult.setData(list);
        } else {
            buluResult.setStatus(1);
            buluResult.setMessage("暂无商品！！！");
        }
        return buluResult;
    }

    // 修改配件米数"[{goodsId:,goodsPrice:,saleNumber:,number:},{},{}]"
    public BuluResult updatePeijian(String peijian) {
        JSONArray jsonArray = JSONArray.parseArray(peijian);
        List<Map<String,Object>> list = new ArrayList<>();
        for (int a = 0; a < jsonArray.size(); a++) {
            JSONObject peijians = (JSONObject) jsonArray.get(a);
            Map<String, Object> map = new HashMap<>();
            Integer goodsId = (Integer) peijians.get("goodsId");
            map.put("goodsId", goodsId);
            Goods goods = customerDao.selectGoodsByGoodsId(goodsId);
            double saleNumber;
            if (peijians.getDouble("saleNumber") != null) {
                saleNumber = peijians.getDouble("saleNumber");
                map.put("saleNumber", saleNumber);
            } else {
                saleNumber = 1;
            }
            map.put("number", peijians.get("number"));
            Sample sample = customerDao.getSampleByGoodId((Integer) peijians.get("goodsId"));
            Double goodsPrice = 0.0;
            if (sample != null) {
                Double price = customerDao.selectPPrice(sample.getSampleId()); // 根据产品号查询配件价格
                goodsPrice = Arith.mul(goods.getNumber(), Arith.mul(price, saleNumber));
            }
            try {
                if (goods.getAcc() != null && "魔术轨".equals((goods.getAcc()))) {
                    goodsPrice += Arith.mul(goods.getNumber(), Arith.mul(goods.getSaleNumber(),
                            customerDao.selectMoshugui()));
                }
            }catch (Exception e){
                e.printStackTrace();
            }

            //壁钩，挂绳计算
            if (goods.getAccessoriesTypeId() == 3 || goods.getAccessoriesTypeId() == 4){
                goodsPrice = Arith.mul(sample.getPrice(),peijians.getDouble("number"));
            }
            map.put("goodsPrice", goodsPrice);
            customerDao.updatePeijian(map);
            Map<String,Object> returnParameter = new HashedMap();
            returnParameter.put("goodsId",goodsId);
            returnParameter.put("goodsPrice",goodsPrice);
            list.add(returnParameter);
            // if(peijians !=null ){
            // Map<String, Object> map = new HashMap<>();
            // map.put("goodsId", peijians.get("goodsId"));
            // Double saleNumber =
            // peijians.getDouble("saleNumber")==null?0.0:peijians.getDouble("saleNumber");
            // map.put("saleNumber", saleNumber);
            // map.put("number", peijians.get("number"));
            // Sample sample =
            // customerDao.getSampleByGoodId((Integer)peijians.get("goodsId"));
            // Double goodsPrice=0.0;
            // if(sample!=null){
            // Double price = customerDao.selectPPrice(sample.getSampleId()); //
            // 根据产品号查询配件价格
            // goodsPrice = Arith.mul(price, saleNumber);
            // }
            // }
        }
        BuluResult buluResult = new BuluResult();
        buluResult.setData(list);
        buluResult.setStatus(0);
        return buluResult;
    }

    // 提交问题反馈
    public BuluResult insertProblem(HttpServletRequest request, String problemCount, String imgs) {
        String sign = (String) request.getParameter("sign");
        if (sign != null) {
            Integer customerId = getIdFromRedis(request);
            Problem problem = new Problem();
            problem.setProblemCount(problemCount);
            problem.setTypeId(customerId);
            problem.setAppId(1);
            Date problemTime = new Date();
            problem.setProblemTime(problemTime);
            customerDao.insertProblem(problem);
            if (imgs != null) {
                JSONArray jsonimgs = JSONArray.parseArray(imgs);
                for (int a = 0; a < jsonimgs.size(); a++) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("img", jsonimgs.get(a));
                    map.put("problemId", problem.getProblemId());
                    customerDao.insertWenti(map);
                }
            }
        } else {
            Problem problem = new Problem();
            problem.setProblemCount(problemCount);
            problem.setAppId(1);
            Date problemTime = new Date();
            problem.setProblemTime(problemTime);
            customerDao.insertProblem(problem);
            if (imgs != null) {
                JSONArray jsonimgs = JSONArray.parseArray(imgs);
                for (int a = 0; a < jsonimgs.size(); a++) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("img", jsonimgs.get(a));
                    map.put("problemId", problem.getProblemId());
                    customerDao.insertWenti(map);
                }
            }
        }
        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        return buluResult;
    }

    // 查询顾客应支付的定金
    public BuluResult selectDingjing(String city) {
        BuluResult buluResult = new BuluResult();
        Double deposit = customerDao.selectDeposit(city);
        if (deposit != null) {
            buluResult.setStatus(0);
            buluResult.setData(deposit);
        } else {
            buluResult.setStatus(1);
            buluResult.setMessage("该城市暂未开通测量!!!");
        }
        return buluResult;
    }

    // 查询工人信息
    public BuluResult selectWorkerX(Integer indentId) {
        Map<String, Object> map = customerDao.selectWorkerX(indentId);
        Indent indent = customerDao.selectIndentInfo(indentId);
        if (indent.getStatus() == 4) {
            Map<String, Object> jing = customerDao.selectJingwei(indentId);
            map.putAll(jing);
        }
        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        buluResult.setData(map);
        return buluResult;
    }

    // 用户未支付测量定金点击返回删除已生成的订单和关系表中的关系---待定
    public BuluResult deleteIndentG(Integer indentId) {
        customerDao.deleteGoodsIndent(indentId);
        customerDao.deleteIndent(indentId);
        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        return buluResult;
    }

    // 根据顾客id获取顾客信息
    public Customer getCustomerById(Integer customerId) {
        Customer customer = customerDao.getCustomerById(customerId);
        return customer;
    }
    @Override
    public Customer getCurrentLoggingCustomer(HttpServletRequest request){
    	return this.getCustomerById(this.getIdFromRedis(request));
    }

    // 暂无用
    public Integer InsertCustomerByPhone(String phone, String referrer) {
        Map<String, Object> map = new HashMap<>();
        map.put("phone", phone);
        map.put("referrer", referrer);
        Integer integer = customerDao.insertCustomerByPhone(map);
        return integer;
    }

    // 根据是什么的配件计算可用什么类型配件
    public BuluResult selectLihaibu(Integer whatStructure, Integer accessoriesTypeId, Integer page) {
        List<Integer> list = new ArrayList<>();
        list.add(accessoriesTypeId);
        // switch (whatStructure) {
        // case 0:// 布配件
        // if (style == 0) {// 打孔
        // list.add(1);
        // } else {// 韩折
        // // 不需要再进行判断以为不管哪种情况可用类型都一样
        // list.add(1);
        // list.add(2);
        // list.add(6);
        // }
        // break;
        // case 1:// 纱配件
        // list.add(1);
        // list.add(2);
        // list.add(6);
        // break;
        // case 2:// 布+纱配件
        // if (style == 0) {// 打孔
        // list.add(1);
        // } else {// 韩折
        // list.add(1);
        // list.add(2);
        // list.add(6);
        // }
        // break;
        // case 3:// 帘头配件
        // list.add(5);
        // break;
        // }
        page = 10 * (page - 1);
        Map<String, Object> map = new HashMap<>();
        map.put("plist", list);
        map.put("page", page);
        List<Sample> samples = customerDao.selectNPeijian(map);
        BuluResult buluResult = new BuluResult();
        if (samples != null && samples.size() > 0) {
            buluResult.setStatus(0);
            buluResult.setData(samples);
        } else {
            buluResult.setStatus(1);
            buluResult.setMessage("没有更多数据了!!!");
        }
        return buluResult;
    }

    // 查询顾客钱包
    public BuluResult selectWallet(HttpServletRequest request) {
        BuluResult buluResult = new BuluResult();
        Integer customerId = getIdFromRedis(request);
        if (customerId == null) {
            buluResult.setStatus(1);
            buluResult.setMessage("该用户已经不存在");
            return buluResult;
        }
        Double wallet = customerDao.selectWallet(customerId);
        buluResult.setStatus(0);
        buluResult.setData(wallet == null ? 0 : wallet);
        return buluResult;
    }

    // 修改顾客钱包
    public BuluResult updateWallet(HttpServletRequest request, double newWalletVal) {
        BuluResult buluResult = new BuluResult();
        BigDecimal bd = new BigDecimal(newWalletVal);
        bd = bd.setScale(2, RoundingMode.HALF_UP);
        Integer customerId = getIdFromRedis(request); // 顾客ID
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("wallet", bd.toString());
        param.put("customerId", customerId);
        customerDao.updateCustomerWallet(param);
        buluResult.setStatus(0);
        buluResult.setData("钱包修改成功");
        return buluResult;
    }

    /**
     * 余额支付 goodsList
     * {goods:[{goodsId:1...},{...},{...},{}],allFee:,earnest:200,appointmentTime:2017-6-8
     * 14:30,measurement:0 }
     */
    @Transactional
    public BuluResult banlancePayment(HttpServletRequest request, Map<String, String> parames) {
        BuluResult buluResult = new BuluResult();
        Double money = Double.parseDouble(parames.get("money"));
        Indent indent = indentDao.selectIndentById(parames.get("indentId"));
        String account = parames.get("account");
        Integer type = Integer.parseInt(parames.get("type"));
        // 数据验证
        if (money == null || indent == null || account == null) {
            buluResult.setStatus(1);
            buluResult.setMessage("参数不能为空");
            return buluResult;
        }
        Customer customer = customerDao.getOneById(getIdFromRedis(request));
        // 验证密码
        JSONObject object = getAccountMap(account);// 解密账号
        if (object == null) {
            buluResult.setStatus(1);
            buluResult.setMessage("账号解析错误");
            return buluResult;
        }
        String pwd = object.getString("password");
        String weiyi = customer.getWeiyi();
        String dataBasePassword = customer.getPassword();
        // 密码比对成功
        if (!(dataBasePassword.equals(MD5Utils.MD5(pwd + weiyi)))) {
            buluResult.setMessage("支付密码错误");
            buluResult.setStatus(1);
            return buluResult;
        }
        if (customer != null && customer.getWallet() != null) {
            // 1 减余额
            if (money.compareTo(customer.getWallet()) > 0) {
                buluResult.setStatus(1);
                buluResult.setMessage("余额不足");
                return buluResult;
            } else {
                Double banlance = customer.getWallet() - money;
                this.updateWallet(request, banlance);
                // 2 修改订单状态
                Map<String, Object> map2 = new HashMap<String, Object>();
                map2.put("indentId", indent.getIndentId());

                if (indent.getIsDelete() == 1) {// 如果是已取消订单，重新支付后从已取消中移除
                    map2.put("isDelete", String.valueOf(0));
                }

                if (indent.getShouldMeasure() == 1) {// 需测量或安装的订单，支付定金后进入待测量阶段（等待接单）
                    if (indent.getStatus() == 4) {
                        map2.put("status", 9);
                        indentDao.updateIndent(map2);

                    } else if (indent.getStatus() == 2) {
                        // 这里应该计算商品价格了，因为工人测量数据已经回来，可根据尺寸计算商品全款价格
//					calcGoodsPrice(indent.getIndentId(), request);
                        map2.put("status", 3);
                        indentDao.updateIndent(map2);
                    } else if (indent.getStatus() == 9 || indent.getStatus() == 3) {
                        indentDao.updateIndent(map2);
                    }
//                    else if (indent.getStatus() == 1 || indent.getStatus() == 5) {// 已接的单子，取消后将单子置为未接
//                        map2.put("acceptTime", "");
//                        map2.put("workerId", "");
//                        indentDao.updateIndent(map2);
//                    }
                } else if (indent.getShouldMeasure() == 0) {
                    map2.put("status", 3);// 无需测量的订单，支付后进入已支付阶段
                    indentDao.updateIndent(map2);
                }
                // 3做消费记录
                CustomerWalletRecord customerWalletRecord = new CustomerWalletRecord();
                customerWalletRecord.setCustomerId(customer.getCustomerId());
                customerWalletRecord.setIndentId(indent.getIndentId());
                customerWalletRecord.setMethod("余额支付");
                customerWalletRecord.setType(type);
                customerWalletRecord.setFinalLostMoney(money);
                customerWalletRecord.setStatus(1);
                customerWalletRecord.setRecordBeginTime(DateUtils.getDateTime());
                customerWalletRecord.setOrderNo(LuKeOrderNoUtil.getCustomerOrderNo
                        (indent.getIndentId(),
                                PayMethod.BALABCEPAY.getIndex(), TypeOfIndent.OTHER.getIndex
                                        ()));
                customerWalletRecord.setRecordEndTime(DateUtils.getDateTime());
                customerWalletRecordService.insertCustomerWalletRecord(customerWalletRecord);
              //分配利润
                if(customerWalletRecord.getIndentId() !=null && customerWalletRecord.getIndentId() !=0){  
                    indentService.updateProfitOfAgentors(customerWalletRecord.getIndentId());
                    Map<String,Object>userCustomerMap=isCustomerOrdered(customerWalletRecord.getIndentId());
    				if(null !=userCustomerMap && !userCustomerMap.isEmpty()){
    					Map<String,Object> map=new HashMap<>();
    					map.put("status", 1);
    					map.put("phone", userCustomerMap.get("phone"));
    					userDao.updateUserCustomer(map);
    				}
                }

                //将推送放到所有操作之后，防止部分操作失败导致支付未成功而推送成功
                if (indent.getShouldMeasure() == 1 && indent.getStatus() == 4 && indent.getType() != null) {
                    // 进行推送 0推送订单 1推送消息
                    // 根据订单号查询订单信息
                    Map<String, Object> indentMap = customerDao.selectIndentMap(indent.getIndentId());
                    if (indentMap == null) {
                        buluResult.setStatus(1);
                        buluResult.setMessage("未查询到订单信息,推送失败");
                        return buluResult;
                    }
                    Jiguang.JpushIndent(indentMap);
                }

                buluResult.setStatus(0);
                buluResult.setMessage("支付成功");
                return buluResult;
            }
        } else {
            buluResult.setStatus(1);
            buluResult.setMessage("支付数据错误");
            return buluResult;
        }
    }

    @Override
    public BuluResult alipayMoney(HttpServletRequest request, Integer indentId, Double money, Integer
            type) {
        BuluResult bulu = new BuluResult();
        System.out.println("=================支付业务开始========================");
        if (indentId == null | money == null) {
            bulu.setStatus(1);
            bulu.setMessage("参数为空");
        }
        // 顾客ID
        Integer customerId = this.getIdFromRedis(request);
        CustomerWalletRecord customerWalletRecord = new CustomerWalletRecord();
        customerWalletRecord.setRecordBeginTime(DateUtils.getDate());
        customerWalletRecord.setCustomerId(customerId);
        customerWalletRecord.setIndentId(indentId);
        customerWalletRecord.setFinalLostMoney(money);
        customerWalletRecord.setType(type);
        customerWalletRecord.setRecordBeginTime(DateUtils.getDate());
        customerWalletRecord.setRemark("订单支付");
        customerWalletRecord.setMethod(PayMethod.ALIPAY.getMethod());
        customerWalletRecord.setOrderNo(LuKeOrderNoUtil.getCustomerOrderNo(indentId,
                PayMethod.ALIPAY.getIndex(),
                TypeOfIndent.OTHER.getIndex()));
        customerWalletRecordService.insertCustomerWalletRecord(customerWalletRecord);
        Indent indent = indentDao.selectIndentById(String.valueOf(indentId));

        Map<String, Object> parames = new HashMap<>();
        parames.put("indentId", indentId);
        parames.put("money", money);
        parames.put("payer", "1");// 顾客支付行为
        Integer payType;
        if (indent.getType() == 1) {//安装费
            payType = TypeOfIndent.INSTALL.getIndex();
        }else {
            payType = TypeOfIndent.OTHER.getIndex();
        }
        parames.put("type", String.valueOf(payType));
        parames.put("customerRecordId", customerWalletRecord.getCustomerWalletRecordId());// 记录ID

        String body = indent.getType() == 0 ? "鹿客家居测量订单" : (indent.getType() == 1 ? "鹿客家居安装订单 " : " 鹿客家居订单 ");
        String subject = body;

        String indentInfo = AlipayParams.getAlipayParams(customerWalletRecord.getOrderNo(), money,
                0.00, body,subject,JSONObject.toJSONString(parames));
        bulu.setStatus(0);
        bulu.setMessage("请求支付成功");
        bulu.setData(indentInfo);
        return bulu;
    }

    /**
     * 功能：充值
     */
    @Override
    public BuluResult recharge(HttpServletRequest request, Double money, Integer method, String
            alipayAccount) {
        // TODO Auto-generated method stub
        BuluResult bulu = new BuluResult();
        System.out.println("=================充值业务开始========================");
        if (money == null | method == null) {
            bulu.setStatus(1);
            bulu.setMessage("参数为空");
        }
        // 顾客ID
        Integer customerId = this.getIdFromRedis(request);

        CustomerWalletRecord customerWalletRecord = new CustomerWalletRecord();
        customerWalletRecord.setRecordBeginTime(DateUtils.getDate());
        customerWalletRecord.setCustomerId(customerId);
        customerWalletRecord.setType(CustomerType.RECHARGE.getIndex());// 1:定金，2:安装费，3:尾款，4:充值, 5:提现6:全配件支付, ',
        customerWalletRecord.setIndentId(0);
        customerWalletRecord.setStatus(0);
        customerWalletRecord.setWalletRecharge(money);// 充值金额
        customerWalletRecord.setFinalGetMoney(money);
        customerWalletRecord.setWalletRecharge(money);// 充值金额

        if (method == 1) {// 支付宝充值
            // 商户转账唯一订单号
            customerWalletRecord.setOrderNo(LuKeOrderNoUtil.getCustomerOrderNo(customerId,
                    PayMethod.ALIPAY.getIndex(),
                    TypeOfIndent.RECHARGE.getIndex()));
            customerWalletRecord.setRemark("支付宝支付");
            customerWalletRecord.setMethod(PayMethod.ALIPAY.getMethod());
            customerWalletRecord.setAlipayNum(alipayAccount);// 充值的支付宝账号

            customerWalletRecordService.insertCustomerWalletRecord(customerWalletRecord);

            Map<String, String> parames = new HashMap<>();
            parames.put("orderNo", customerWalletRecord.getOrderNo());
            parames.put("money", money.toString());
            parames.put("payer", "1");// 顾客支付行为
            parames.put("type", String.valueOf(TypeOfIndent.RECHARGE.getIndex()));
            parames.put("recharge", "customerRecharge");
            parames.put("customerRecordId", String.valueOf
                    (customerWalletRecord.getCustomerWalletRecordId()));
            String body = "支付宝充值";
            String subject = body;
            String indentInfo = AlipayParams.getAlipayParams(parames.get("orderNo"),
                    Double.parseDouble(parames.get("money")), 0.00, body, subject,
                    JSONObject.toJSONString(parames));
            bulu.setStatus(0);
            bulu.setData(indentInfo);
            return bulu;
        } else {
            System.out.println("其他充值接口");
        }
        bulu.setStatus(1);
        bulu.setMessage("充值失败");
        System.out.println("=================充值业务结束========================");
        return bulu;
    }

    // 计算商品价格
    private double calcGoodsPrice(Integer indentId, HttpServletRequest request) {
        // TODO Auto-generated method stub
        double indentPrice = 0;
        List<Goods> goodss = customerDao.getGoodByIndentId(customerDao.getGoodIdByIndentId(indentId));
        for (Goods goods : goodss) {
            if (goods.getType() == 0) {//布艺帘

            } else if (goods.getType() == 1) {

            }
            Map<String, Object> map = new HashMap<>();
            map.put("goodsId", goods.getGoodsId());
            map.put("customerId", getIdFromRedis(request));
            Goods goodsList = customerDao.getGoodsToCaclPriceByGoodsId(map);
            Map<String, Object> map1 = new HashMap<>();
            map1.put("goodsId", goods.getGoodsId());
            indentPrice += Double.parseDouble(priceService.curtainPrice(goodsList).getData
                    ().toString());
        }
        return indentPrice;
    }

    // 查询账号绑定情况
    public BuluResult selectBangding(HttpServletRequest request) {
        Integer customerId = getIdFromRedis(request);
        Integer yinhang = customerDao.selectBangding(customerId);
        Integer weixin = customerDao.selectWeixin(customerId);
        Integer zhifubao = customerDao.selectZhifubao(customerId);
        Map<String, Object> send = new HashMap<>();
        if (yinhang == 1) {
            send.put("yinhangka", 0);
        } else {
            send.put("yinhangka", 1);
        }
        if (weixin == 1) {
            send.put("weixin", 0);
        } else {
            send.put("weixin", 1);
        }
        if (zhifubao == 1) {
            send.put("zhifubao", 0);
        } else {
            send.put("zhifubao", 1);
        }
        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        buluResult.setData(send);
        return buluResult;
    }

    // 添加银行卡
    public BuluResult insertYinhangka(HttpServletRequest request, String bankName, String boundBank,
                                      String bankNumber) {
        Integer customerId = getIdFromRedis(request);
        Map<String, Object> map = new HashMap<>();
        map.put("customerId", customerId);
        map.put("bankName", bankName);
        map.put("boundBank", boundBank);
        map.put("bankNumber", bankNumber);
        customerDao.updateBank(map);
        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        return buluResult;
    }

    // 添加支付宝
    public BuluResult insertZhifubao(HttpServletRequest request, String baoName, String zhifubao) {
        Integer customerId = getIdFromRedis(request);
        Map<String, Object> map = new HashMap<>();
        map.put("customerId", customerId);
        map.put("baoName", baoName);
        map.put("zhifubao", zhifubao);
        customerDao.updateZhifubao(map);
        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        return buluResult;
    }

    // 添加微信
    public BuluResult insertWeixin(HttpServletRequest request, String xinName, String weixin) {
        Integer customerId = getIdFromRedis(request);
        Map<String, Object> map = new HashMap<>();
        map.put("customerId", customerId);
        map.put("xinName", xinName);
        map.put("weixin", weixin);
        customerDao.updateWeixin(map);
        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        return buluResult;
    }

    // 购物车中生成order后取消 删除订单及一些影响
    public BuluResult callbackOrder(HttpServletRequest request, Integer orderId) {
        Integer success = customerDao.selectYanzheng(orderId);
        BuluResult buluResult = new BuluResult();
        if (success == 1) {
            customerDao.updateGoodsO(orderId);
            customerDao.deleteQOrder(orderId);
            buluResult.setStatus(0);
        } else {
            buluResult.setStatus(1);
            buluResult.setMessage("订单号传入有误!!!");
        }
        return buluResult;
    }

    /**
     * 下订单（测量单或者新订单）
     * goods={goodsAndAcc:[{goodsId:,},],cuAdId:,subscribeTime:预约测量是时间}
     */
    @Override
    @Transactional
    public BuluResult insertIndent(HttpServletRequest request, String goodsList) {
        BuluResult buluResult = new BuluResult();
        Double allFee = null, earnest = null;
        String city = null;
        Date appointmentTime = null;
        JSONObject jsonObj = JSONObject.parseObject(goodsList);
        if (jsonObj == null) {
            buluResult.setStatus(1);
            buluResult.setMessage("参数传递错误,无法解析");
            return buluResult;
        }
        String receiver = jsonObj.getString("receiver");// 收货人
        String receiverPhone = jsonObj.getString("receiverPhone");// 收货人电话
        String remark = jsonObj.getString("remark");// 备注
        Integer cuAdId = jsonObj.getInteger("cuAdId");// 收货地址Id
        JSONArray list = JSONArray.parseArray(jsonObj.getString("goods"));// 商品集合
        Integer shouldMeasure = jsonObj.getInteger("shouldMeasure");// 是否需要测量

        // 0：不需要1：需要
        allFee = jsonObj.getDouble("allFee"); // 全配件- 总额--order
        if (shouldMeasure == 1) {
            earnest = jsonObj.getDouble("earnest"); // 布艺帘- 定金
            city = jsonObj.getString("city");// 布艺帘-城市
            appointmentTime = new Date(jsonObj.getLong("appointmentTime")); // 布艺帘-预约时间
        }else {
            appointmentTime = new Date();
        }
        // 数据验证
        if (receiver == null || receiver.trim().length() == 0 || receiverPhone == null || cuAdId ==
                null
                || receiverPhone.trim().length() == 0 || shouldMeasure == null) {
            buluResult.setStatus(1);
            buluResult.setMessage("用户信息不能为空");
            return buluResult;
        }
        // 1.生成订单
        Indent indent = new Indent();
        indent.setBeginTime(new Date());// 下单时间
        indent.setIndentType(0);// '0 顾客下的单 1测量日记(鹿客帮用) 2后台人员 3商家下单 4其他待定',
        indent.setSubscribeTime(appointmentTime);// 预约时间
        indent.setType(shouldMeasure == 0 ? 4 : 0);// '订单类型 0平台测量
        // 1安装2维修3经销商自主测量的 ',4纯配件订单
        indent.setStatus(4);// 等待付款
        Customer_address address = customerDao.selectAddress(cuAdId);
        address.setStatus(null);
        customerDao.insertNewAddress(address);
        indent.setCuAdId(address.getCuAdId());// '地址ID',
        indent.setCustomerPrice(shouldMeasure == 1 ? 0.0 : allFee);// 实付金额
        indent.setCustomerId(getIdFromRedis(request));// '顾客ID（包括其他id）',
        indent.setTakeGoodsTel(receiverPhone);// 收货电话（tel）
        indent.setRemark(remark);// 备注
        indent.setShouldMeasure(shouldMeasure);// 是否需要测量 0:不测1测
        indent.setIndentSource(2);//订单来源：0 app下单，1 网页下单，2 家居版下单
        customerDao.insertIndent(indent);

        // 2.清空购物车，关联订单与购物车中商品
        for (int i = 0; i < list.size(); i++) {
            // 清除购物车商品
            JSONObject goodsJson = JSONObject.parseObject(list.get(i).toString());
            if (goodsJson != null) {
                Integer goodsId = goodsJson.getInteger("goodsId");
                if (goodsId == null) {
                    buluResult.setStatus(1);
                    buluResult.setMessage("商品ID不能为空");
                    return buluResult;
                }
                Goods goods = new Goods();
                goods.setGoodsId(goodsId);
                goods.setIsCar(0);
                goodsDao.updateGoods(goods); // 非购物车
                // 关联goods和indent
                Map<String, Object> map1 = new HashMap<>();
                map1.put("goodsId", goods.getGoodsId());
                map1.put("indentId", indent.getIndentId());
                customerDao.insertGood_Indent(map1);
            }
        }

        // 3计算测量费
        if (shouldMeasure == 1) {
            Integer roomNumB = customerDao.selectDistinct(indent.getIndentId())
                    + customerDao.selectOtherRoom(indent.getIndentId());
            // room.put("indentId", indent.getIndentId());
            // room.put("roomNumB", roomNumB);
            indent.setRoomNumB(roomNumB);
            // 计算测量费
            city = customerDao.getAddressById(cuAdId).getCity();
            // 测量安装费 type:工人版0 商家版1
            Map<String, Object> map = customerDao.selectCPriceByCity(city, 1);
            Map<String, Object> mapGR = customerDao.selectCPriceByCity(city, 0);
            Double indentPrice = 0.0;
            Double customerPrice = 0.0;

            customerPrice = meaPrice(map, roomNumB, customerPrice);
            indentPrice = meaPrice(mapGR, roomNumB, indentPrice);// 测量费用

            // 测量费估计也得在这加(修改插入语句中加入测量费)
            // room.put("indentPrice", indentPrice);
            // room.put("customerPrice", customerPrice);
            // room.put("merchantsRealPrice", indentPrice);
            // room.put("deposit", earnest+indentPrice);

            indent.setIndentPrice(indentPrice);// 测量费/安装费（工人版）
            indent.setCustomerPrice(customerPrice);// 测量费/安装费（商家版）
            indent.setWorkerRealPrice(indentPrice);
            indent.setMerchantsRealPrice(customerPrice);
            indent.setDeposit(earnest);// 定金=测量费+押金(押金暂时没有，以后添加)
            customerDao.updateMeterIndent(indent);

        }
        // 4订单id得到所有的商品id--返回订单所有商品
        Map<String, Object> map2 = new HashMap<>();
        List<Integer> goods_indents = customerDao.getGoodIdByIndentId((int) indent.getIndentId());
        List<Map<String, Object>> samples = new ArrayList<>();
        for (Integer goodsId : goods_indents) {
            // 得到样品id和样品图片
            Map<String, Object> img = customerDao.getSampleByGoodId2(goodsId);
            if (img != null)
                img.put("acces", getAcces(goodsId));
            samples.add(img);
        }

        Indent indent2 = indentDao.selectIndentById(String.valueOf(indent.getIndentId()));

        if (shouldMeasure == 1) {// 需要测量的
            map2.put("subscribeTime", indent2.getSubscribeTime());// 预约时间
            map2.put("indentPrice", indent2.getIndentPrice());// 测量费
            map2.put("deposit", customerDao.selectTerritoryByType(10).getMoney());// 定金
        }
        map2.put("samples", samples);// 样品集合
        map2.put("shouldMeasure", shouldMeasure);
        map2.put("beginTime", indent2.getBeginTime());// 下单时间
        map2.put("indentId", indent2.getIndentId());// 订单id
        map2.put("customerPrice", indent2.getCustomerPrice());
        map2.put("status", indent2.getStatus());// 订单状态
        map2.put("type", indent2.getType());// 订单类型
        buluResult.setStatus(0);
        buluResult.setData(map2);
        buluResult.setMessage("订单已经提交成功");
        return buluResult;
    }

    /**
     * 计算定金
     */
    @Override
    public BuluResult requestEarnest(HttpServletRequest request, String curtainNum, String city) {
        BuluResult buluResult = new BuluResult();
        if (curtainNum == null || "".equals(curtainNum) || city == null|| "".equals(city)) {
            buluResult.setStatus(1);
            buluResult.setMessage("参数缺失");
            return buluResult;
        }
        // 计算测量费
        Map<String, Object> map = customerDao.selectCPriceByCity(city, 1);
        Map<String, Object> mapGR = customerDao.selectCPriceByCity(city, 0);
        Double indentPrice = 0.0;
        Double customerPrice = 0.0;

        customerPrice = meaPrice(map, Integer.parseInt(curtainNum), customerPrice);
        indentPrice = meaPrice(mapGR, Integer.parseInt(curtainNum), indentPrice);

        Map<String, Object> room = new HashMap<>();
        // 测量费估计也得在这加(修改插入语句中加入测量费)
        room.put("indentPrice", indentPrice);
        room.put("customerPrice", customerPrice);
        room.put("workerRealPrice", indentPrice);
        room.put("merchantsRealPrice", customerPrice);
        customerDao.updateIndentRoom(room);
        // customerDao.updateIndent(mapGR);

        Double deposit = customerDao.selectTerritoryByType(10).getMoney();//押金

        buluResult.setStatus(0);
        buluResult.setData(Arith.add(customerPrice,deposit));
        buluResult.setMessage("结果：定金金额(包含测量费和押金)");
        return buluResult;
    }

    // 获取一定窗帘数量的测量价格
    private double meaPrice(Map<String, Object> map, int roomNumB, double price) {
        double meaStartingFare = (double) map.get("meaStartingFare");// 测量起步价
        int meaBeyondNumOne = (Integer) map.get("meaBeyondNumOne");// 第一个阈值
        int meaBeyondNumTwo = (Integer) map.get("meaBeyondNumTwo"); // 第二个阈值
        double meaBeyUnitPriceOne = (double) map.get("meaBeyUnitPriceOne");// 过了第一个阈值后每个数据单价
        double meaBeyUnitPriceTwo = (double) map.get("meaBeyUnitPriceTwo");// 过了第二个阈值每个数据单价
        if (roomNumB <= 0) {// 测量房间数小于等于0
            price = 0;
        } else if (meaBeyondNumOne >= roomNumB && roomNumB > 0) {// 测量房间数不超过第一个阀值(10)
            price = Arith.add(meaStartingFare, price);
        } else if (meaBeyondNumOne < roomNumB && meaBeyondNumTwo >= roomNumB) {// 大于第一个，小于等于第二个
                    price = Arith.add((roomNumB - meaBeyondNumOne) * meaBeyUnitPriceOne, meaStartingFare);
        } else {
            price = Arith.add(Arith.add(10 * meaBeyUnitPriceOne, meaStartingFare),
                    (roomNumB - meaBeyondNumTwo) * meaBeyUnitPriceTwo);
        }
        return price;
    }

    /**
     * 下安装单 goodIds="{indentId:4433,subscribeTime:,city:}"
     */
    @Transactional
    public BuluResult insertAzhuang(HttpServletRequest request, String goodIds) {
        BuluResult buluResult = new BuluResult();
        JSONObject jsonObject = JSONObject.parseObject(goodIds);
        if (jsonObject == null) {
            buluResult.setStatus(1);
            buluResult.setMessage("传输数据有误，无法解析");
            return buluResult;
        }
        // 计算安装费
        Double indentPrice = 0.00;
        Double customerPrice = 0.00;
        Integer cuAdId = jsonObject.getInteger("cuAdId");// 收货地址Id
        String city = jsonObject.getString("city");
        Integer indentId = jsonObject.getIntValue("indentId");
        String remark = jsonObject.getString("remark");// 备注
        List<Integer> list = customerDao.getGoodsIdsByIndentId(indentId);//通过订单id，获得该订单下的所有商品
        Indent indent1 = indentDao.selectIndentById(jsonObject.getString("indentId"));// 订单
        if (indent1 != null){
            Map<String,Double> result = countAzhuangMoney(city, list, indent1.getShouldMeasure());           
            indentPrice = result.get("indentPrice");
            customerPrice = result.get("customerPrice");
        }
        if (indentPrice == 0.00 || customerPrice == 0.00) {
            buluResult.setStatus(1);
            buluResult.setMessage("安装费用计算为0.0");
            return buluResult;
        }
        // 2生成安装单据
        Indent indent = new Indent();
        indent.setBeginTime(new Date());// 下单时间
        indent.setIndentType(0);// 顾客下单
        Customer_address address = customerDao.selectAddress(cuAdId);
        address.setStatus(null);
        customerDao.insertNewAddress(address);
        indent.setCuAdId(address.getCuAdId());// '地址ID',
        indent.setSubscribeTime(jsonObject.getDate("subscribeTime"));// 预约安装时间
        indent.setType(1);// 安装单
        indent.setIndentPrice(indentPrice);// 安装费用(给工人)
        indent.setCustomerPrice(customerPrice);// 安装费用(从客户收取)
        indent.setStatus(4);// 等待付款
        indent.setIndentSource(2);//订单来源：0 app下单，1 网页下单，2 家居版下单
        indent.setShouldMeasure(1);// 需要安装
        indent.setRemark(remark);// 备注
        indent.setCustomerId(getIdFromRedis(request));// 顾客ID
        indent.setRoomNumB(indent1.getRoomNumB());
        customerDao.insertIndent(indent);
        // 3.1:关联订单和安装物品
        for (Integer goodsId : list) {
            Map<String, Object> map1 = new HashMap<>();
            map1.put("goodsId", goodsId);
            map1.put("indentId", indent.getIndentId());
            customerDao.insertGood_Indent(map1);
        }
        // 4返回安装单数据
        List<Integer> goods_indents = customerDao.getGoodIdByIndentId((int) indent.getIndentId());
        List<Map<String, Object>> samples = new ArrayList<Map<String, Object>>();
        for (Integer goodsId : goods_indents) {
            // 得到样品id和样品图片
            Map<String, Object> img = customerDao.getSampleByGoodId2(goodsId);
            if (img != null)
                img.put("acces", getAcces(goodsId));
            samples.add(img);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("beginTime", indent.getBeginTime());
        map.put("indentPrice", indent.getIndentPrice());
        map.put("customerPrice", indent.getCustomerPrice());
        map.put("indentId", indent.getIndentId());
        map.put("deposit", customerDao.selectTerritoryByType(10).getMoney());
        map.put("status", indent.getStatus());
        map.put("samples", samples);
        buluResult.setStatus(0);
        buluResult.setData(map);
        return buluResult;
    }

    /**
     * 功能：计算安装费用
     *
     * @param city
     * @return
     */
    public Map<String,Double> countAzhuangMoney(String city, List<Integer> list, Integer
            shouldMeasure) {
        Double indentPrice = 0.0;
        Double customerPrice = 0.0;
        Map<String,Double> returnResult = new HashMap<>();
        if (city == null || "".equals(city) || list == null || list.size() == 0) {
            returnResult.put("indentPrice", indentPrice);
            returnResult.put("customerPrice", customerPrice);
            return returnResult;
        }
        Double installStartingFare = 0.0;// 安装起步价
        for (Integer id : list) { // 遍历订单下所有商品
            Goods goods = goodsDao.selectGoodsById(id);
            if (goods == null){
                returnResult.put("indentPrice",indentPrice);
                returnResult.put("customerPrice",customerPrice);
                return returnResult;
            }
            List<Map<String, Object>> parsAcc = new ArrayList<Map<String, Object>>();
            if (goods.getType() == 2) {// 配件
                List<Map<String, Object>> parsList = customerDao.getParsGoods(id);
                parsAcc.addAll(parsList);
            } else {// 布艺帘-成品帘
                List<Map<String, Object>> parsList = customerDao.getParsGoodsIdsByGoodsId(id);
                parsAcc.addAll(parsList);
            }
            if (parsAcc.size() == 0) {
                returnResult.put("indentPrice",indentPrice);
                returnResult.put("customerPrice",customerPrice);
                return returnResult;
            }
            p:
            for (Map<String, Object> pars : parsAcc) {// 遍历配件
                //给工人的价
                Map<String, Object> workerParas = new HashMap<>();
                workerParas.put("city", city);
                workerParas.put("ttype", 0);
                workerParas.put("ctype", pars.get("accessoriesType"));
                workerParas.put("number", pars.get("number"));
                Cost_rules workerRule = customerDao.selectAPriceByCity(workerParas); // 所在城市安装情况
                //客户付我们的价
                Map<String, Object> paras = new HashMap<>();
                paras.put("city", city);
                paras.put("ttype", 1);
                paras.put("ctype", pars.get("accessoriesType"));
                paras.put("number", pars.get("number"));
                Cost_rules rule = customerDao.selectAPriceByCity(paras); // 所在城市安装情况
                if (rule == null || workerRule == null)
                    continue p;
                if (installStartingFare == 0.0)
                    installStartingFare = rule.getInstallStartingFare();// 起步价
                Integer number = Integer.valueOf(pars.get("number") == null ? "0" : pars.get
                        ("number").toString());// 单双（单杆/双杆）
                Double workerBase = (number == 1 ? workerRule.getSingle() : (number == 2 ?
                        workerRule.getDoubleDeck() : null));// 安装基础费用--工人
                Double base = (number == 1 ? rule.getSingle() : (number == 2 ?
                        rule.getDoubleDeck() : null));// 安装基础费用
                if (base != null && workerBase != null) {
                    Double installPrice;
                    // 按照3.5*4计算
                    if (shouldMeasure == 0) {
                        indentPrice += workerBase;
                        customerPrice += base;
                        installPrice = workerBase;
                    } else {
                        Double width = Double.valueOf(pars.get("wide") == null ? "0" :
                                pars.get("wide").toString());// 实际宽
                        Double heigh = Double.valueOf(pars.get("high") == null ? "0" :
                                pars.get("high").toString());// 实际高
                        if (width == 0.0 || heigh == 0.0)
                            continue p;

                        Double widthBasisMeter = rule.getWidthBasisMeter(); // 基础宽
                        Double heightBasisMeter = rule.getHeightBasisMeter();// 基础高

                        Double widthBeyondMeter = rule.getWidthBeyondMeter();// 超出宽（米）
                        Double heightBeyondMeter = rule.getHeightBeyondMeter();// 超出高（米）

                        Double heightBeyondUnitPrice = rule.getHeightBeyondUnitPrice
                                ();// 超出高加价
                        if ( widthBasisMeter <= 0
                                || heightBasisMeter <= 0 || widthBeyondMeter
                                <= 0 || heightBeyondMeter <= 0
                                || heightBeyondUnitPrice <= 0) {
                            returnResult.put("indentPrice",indentPrice);
                            returnResult.put("customerPrice",customerPrice);
                            return returnResult;
                        }
                        // 超出基础高，重新算Base价格;
                        if (heigh > heightBasisMeter) {
                            base += Math.ceil((heigh - heightBasisMeter) /
                                    heightBeyondMeter) * heightBeyondUnitPrice;
                            workerBase += Math.ceil((heigh - heightBasisMeter) /
                                    heightBeyondMeter) * heightBeyondUnitPrice;
                        }
                        // 超出宽的加倍累计
                        if (width <= widthBasisMeter) {
                            indentPrice += workerBase;
                            customerPrice += base;
                            installPrice = workerBase;
                        } else {
                            indentPrice += workerBase * (Math.ceil((width -
                                    widthBasisMeter) / widthBeyondMeter) + 1);
                            customerPrice += base * (Math.ceil((width -
                                    widthBasisMeter) / widthBeyondMeter) + 1);
                            installPrice = workerBase * (Math.ceil((width -
                                    widthBasisMeter) / widthBeyondMeter) + 1);
                        }
                    }
                    Map<String,Object> map = new HashMap();
                    map.put("goodsId",id);
                    map.put("installPrice",installPrice);
                    customerDao.updateGoodByGoodId(map);
                }
            }
        }
        // 返回安装费--工人
        if (indentPrice != 0.0 && indentPrice < installStartingFare) {
            indentPrice = installStartingFare;
        }
        // 返回安装费
        if ((customerPrice != 0.0 && customerPrice < installStartingFare) || shouldMeasure == 0) {
            customerPrice = installStartingFare;
        }
        System.out.println("indentPrice:" + indentPrice);
        returnResult.put("indentPrice",indentPrice);
        returnResult.put("customerPrice",customerPrice);
        return returnResult;
    }

    // 查询物流根据订单号
    public BuluResult selectWuliu(Integer orderId) {
        // 根据订单号查询这个订单都有哪些物流号
        List<String> wulius = customerDao.selectWuliuhao(orderId);
        List<Map<String, Object>> list = new ArrayList<>();
        for (int a = 0; a < wulius.size(); a++) {
            Map<String, Object> map = new HashMap<>();
            String LogisticCode = wulius.get(a);
            Map<String, Object> send = new HashMap<>();
            send.put("orderId", orderId);
            send.put("logistics", LogisticCode);
            // 根据物流号查询这个订单中的这个单的商品图像
            List<String> imgs = customerDao.selectImgs(send);
            map.put("imgs", imgs);
            // 根据订单号查询物流信息
            KdApiOrderDistinguish api = new KdApiOrderDistinguish();
            KdniaoTrackQueryAPI api2 = new KdniaoTrackQueryAPI();
            String result = null;
            try {
                String wuliuGongsi = api.getOrderTracesByJson(LogisticCode);
                JSONObject jsonObject = JSONObject.parseObject(wuliuGongsi);
                JSONArray jsonArray = jsonObject.getJSONArray("Shippers");
                JSONObject jsonObject2 = null;
                if (jsonArray.size() > 0) {
                    jsonObject2 = jsonArray.getJSONObject(0);
                }
                String string = jsonObject2.getString("ShipperCode");
                result = api2.getOrderTracesByJson(string, LogisticCode);
                JSONObject object = JSONObject.parseObject(result);
                map.put("wuliu", object);
            } catch (Exception e) {
                e.printStackTrace();
            }
            list.add(map);
        }
        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        buluResult.setData(list);
        return buluResult;
    }

    // 查询app启动广告
    public BuluResult selectGuanggao() {
        List<String> guanggao = customerDao.selectGuanggao();
        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        buluResult.setData(guanggao);
        return buluResult;
    }

    // 根据商品号查询商品
    public BuluResult selectGoodxinxi(Integer goodsId) {
        Map<String, Object> map = workerDao.selectGoodxinxi(goodsId);
        if ((Integer) map.get("type") == 0) {// 布艺帘
            List<Map<String, Object>> list = workerDao.selectSpecial(goodsId);
            for (int a = 0; a < list.size(); a++) {
                List<String> imgs = workerDao.selectImgs((Integer) list.get(a).get
                        ("specialId"));
                list.get(a).put("imgs", imgs);
                // 获得安装位置拍照
                List<String> installImgs = workerDao.selectInstallImgs((Integer) list.get
                        (a).get("specialId"));
                list.get(a).put("installImgs", installImgs);
            }
            map.put("specials", list);
        } else {// 成品帘
            // 根据goodsId查找旗下的所有special参数
            List<Map<String, Object>> list = workerDao.selectFinishSpecial(goodsId);
            for (int a = 0; a < list.size(); a++) {
                // 查找该special下的照片
                List<String> imgs = workerDao.selectChengpinImgs((Integer) list.get(a).get
                        ("specialId"));
                list.get(a).put("imgs", imgs);
                // 获得安装位置拍照
                List<String> installImgs = workerDao.selectInstallImgs((Integer) list.get
                        (a).get("specialId"));
                list.get(a).put("installImgs", installImgs);
                Goods goods = workerDao.selectGoodsInfo((Integer) list.get(a).get("accId"));
                list.get(a).put("pinstallSite", goods.getPinstallSite());
            }
            map.put("specials", list);
            List<String> installImgs = workerDao.selectImgsCplInstall((Integer) map.get
                    ("goodsId"));
            map.put("installImgs", installImgs);
        }

        if (map.get("locationId") != null) {
            String locationContent = workerDao.selectLocationConent((Integer) map.get
                    ("locationId"));
            map.put("locationContent", locationContent);
        } else {
            map.put("locationContent", map.get("otherRoom"));
        }
        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        buluResult.setData(map);
        return buluResult;
    }

    // @Override
    // public BuluResult alipayResult(HttpServletRequest request) {
    // // TODO Auto-generated method stub
    // BuluResult buluResult = new BuluResult();
    // Map<String, String> params = new HashMap<String, String>();
    // Map<String, String[]> requestParams = request.getParameterMap();
    // for (Iterator<String> iter = requestParams.keySet().iterator();
    // iter.hasNext();) {
    // String name = (String) iter.next();
    // String[] values = (String[]) requestParams.get(name);
    // String valueStr = "";
    // for (int i = 0; i < values.length; i++) {
    // valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr +
    // values[i] + ",";
    // }
    // // 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
    // // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
    // params.put(name, valueStr);
    // }
    // // 商户订单号
    // String out_trade_no = "";
    // // 支付宝交易号
    // // String trade_no = "";
    // // 交易状态
    // String trade_status = "";
    // // 异步通知ID
    // String notify_id = "";
    //
    // String total_fee = "";
    //
    // // sign
    // String sign = "";
    //
    // // 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
    // try {
    // // 商户订单号
    // out_trade_no = new
    // String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),
    // "UTF-7");
    //
    // // 支付宝交易号
    // // trade_no = new
    // //
    // String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-7");
    //
    // // 交易状态
    // trade_status = new
    // String(request.getParameter("trade_status").getBytes("ISO-8859-1"),
    // "UTF-7");
    //
    // // 交易金额
    // total_fee = new
    // String(request.getParameter("total_fee").getBytes("ISO-8859-1"),
    // "UTF-7");
    //
    // // 异步通知ID
    // notify_id = request.getParameter("notify_id");
    //
    // // sign
    // sign = request.getParameter("sign");
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    //
    // if (notify_id != "" && notify_id != null) {
    // if (AlipayNotify.verifyResponse(notify_id).equals("true")) {//
    // 判断成功之后使用getResponse方法判断是否是支付宝发来的异步通知。
    // if (AlipayNotify.getSignVeryfy(params, sign)) {// 使用支付宝公钥验签
    // if (trade_status.equals("TRADE_FINISHED") ||
    // trade_status.equals("TRADE_SUCCESS")){
    // //0.交易记录
    // //1.修改订单状态
    // if(!("".equals(out_trade_no))){
    // Indent indent=indentDao.selectIndentById(out_trade_no);
    // if(indent !=null){
    // Integer type=indent.getType();
    // switch (type) {
    // case 0://测量
    // if(indent.getStatus()==4) indent.setStatus(9);
    // if(indent.getStatus()==2) indent.setStatus(3);
    // break;
    // case 1: //安装
    // if(indent.getStatus()==4) indent.setStatus(9);
    // break;
    // case 4://普通订单
    // indent.setStatus(3);
    // default:
    // break;
    // }
    // customerDao.updateMeterIndent(indent);
    // }
    // }
    // }
    // buluResult.setStatus(0);
    // buluResult.setMessage("支付成功");
    // }else{
    // buluResult.setStatus(1);
    // buluResult.setMessage("验证签名失败!!!");
    // }
    // }else{
    // buluResult.setStatus(2);
    // buluResult.setMessage("验证是否来自支付宝的通知失败!!!");
    // }
    // }else{
    // buluResult.setStatus(3);
    // buluResult.setMessage("未接收到支付宝的通知!!!");
    // }
    // return buluResult;
    // }
    //

    /**
     * 对账号和密码进行解密
     *
     * @param account
     * @param type    1:代表解密后为JSONObject对象 2:代表解密的是密码
     * @return
     */
    private JSONObject getAccountMap(String account, int type) {
        JSONObject map = new JSONObject();
        try {
            account = AESCipher.aesDecryptString(account, Constant.ENCRYPTKEY);
            map = JSONObject.parseObject(account);
            logger.error("<=========工人登陆的账户和密码：" + map);
        } catch (Exception e) {
            logger.error("===============工人解密时出现错误" + account + "==================");
            return map;
        }
        return map;
    }

    // 查询提现明细
    public BuluResult selectMingxi(HttpServletRequest request, Integer page) {
        String sign = request.getParameter("sign");
        Integer customerId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 5));
        Map<String, Object> map = new HashMap<>();
        // 他们传过来的page初始值为1
        page = 10 * ((page == null ? 1 : page) - 1);// 计算每一页从第几条记录开始查询
        map.put("page", page);
        map.put("customerId", customerId);
        List<Map<String, Object>> list = customerDao.selectMingxi(map);
        BuluResult buluResult = new BuluResult();
        if (list != null && list.size() > 0) {
            buluResult.setStatus(0);
            buluResult.setData(list);
        } else {
            buluResult.setStatus(1);
            buluResult.setMessage("没有提现数据!!!");
        }
        return buluResult;
    }

    /**
     * 工人提现到支付宝
     */
    @Override
    public BuluResult alipyWithdrawal(HttpServletRequest request, Double money, String zhifubao, String
            name,
                                      String account, Integer status) {
        logger.error("=======================================顾客提现到支付宝开始 =========================================");
        // 返回参数
        BuluResult buluResult = new BuluResult();
        // 提取工人id
        String sign = request.getParameter("sign");
        Integer customerId = Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 5));
        // 比较输入金额和钱包
        Customer customer = customerDao.getCustomerById(customerId);
        JSONObject object = getAccountMap(account, 2);
        String password = object.getString("password");
        buluResult = checkWithdrawalParams(money, zhifubao, name, password, customer);
        if (buluResult.getStatus() == 1) {
            return buluResult;
        }
        // 钱包提现到支付宝
        CustomerWalletRecord customerWalletRecord = new CustomerWalletRecord();
        customerWalletRecord.setCustomerId(customerId);
        customerWalletRecord.setType(CustomerType.WITHDRAWALS.getIndex());
        customerWalletRecord.setWalletWithdrawals(money);
        customerWalletRecord.setRecordBeginTime(DateUtils.getDateTime());
        // 商户转账唯一订单号
        customerWalletRecord.setOrderNo(LuKeOrderNoUtil.getCustomerOrderNo(customerId,
                PayMethod.ALIPAY.getIndex(),
                TypeOfIndent.WITHDRAWALS.getIndex()));
        /*
         * // 类型是工人 MoneyRecord moneyRecord = new MoneyRecord();
		 * moneyRecord.setPeopleId(workerId); moneyRecord.setType(1);
		 * moneyRecord.setMoney(money); Date date = new Date();
		 * moneyRecord.setRecordTime(date); moneyRecord.setStatus(status); //
		 * 商户转账唯一订单号 String outBizNo = MD5Utils.MD5(String.valueOf(new
		 * Date().getTime() + "-" + worker.getWorkerId()));
		 * moneyRecord.setOutBizNo(outBizNo);
		 */
        if (status == 1) {// 支付宝方式
            customerWalletRecord.setMethod(PayMethod.ALIPAY.getMethod());
            customerWalletRecord.setRemark("支付宝提现");
            customerWalletRecord.setAlipayNum(zhifubao);
			/*
			 * moneyRecord.setZhifubao(zhifubao); moneyRecord.setName(name);
			 */
            // 调用支付宝转账接口
            buluResult = alipyFundTransToaccountTransfer(customerWalletRecord, zhifubao, money,
                    name, customerId,
                    customer);
        } else {
            buluResult.setStatus(1);
            buluResult.setMessage("其他提现方式正在开通，敬请期待");
        }
        return buluResult;
    }

    /**
     * 验证提现时参数的正确和合法性
     *
     * @param money
     * @param zhifubao
     * @param name
     * @param password
     * @param customer
     * @return
     */
    private BuluResult checkWithdrawalParams(Double money, String zhifubao, String name, String password, Customer customer) {
        logger.error("=======================================顾客提现前的参数检验 =========================================");
        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        if (customer.getWallet().compareTo(money) < 0) {
            buluResult.setStatus(1);
            buluResult.setMessage("提现金额大于钱包余额");
            return buluResult;
        }
        // 比较密码
        password = MD5Utils.MD5(password + customer.getWeiyi());
        if (!password.equals(customer.getPassword())) {
            buluResult.setStatus(1);
            buluResult.setMessage("密码不对,请重新输入");
            return buluResult;
        }
        if (!(customer.getZhifubao().equals(zhifubao) && customer.getName().equals(name))) {
            buluResult.setStatus(1);
            buluResult.setMessage("提现人姓名或者支付宝账号不对");
            return buluResult;
        }
        return buluResult;
    }

    /**
     * 单笔打款到某一个支付宝账户
     *
     * @param customerWalletRecord 本次转账记录
     * @param zhifubao             金额到账的目标账号
     * @param money                转账的钱
     * @param name                 账号的名字
     * @param customerId           转账人的id
     * @return
     */
    private BuluResult alipyFundTransToaccountTransfer(CustomerWalletRecord customerWalletRecord, String
            zhifubao,Double money, String name, Integer customerId, Customer customer) {
        logger.error("=======================================顾客提现到支付宝请求开始 =========================================");
        BuluResult buluResult = new BuluResult();
        // 实例化客户端
        AlipayClient alipayClient0 = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                AlipayConfig.app_id, AlipayConfig.app_private_key, "json", "utf-8",
                AlipayConfig.alipay_public_key,
                "RSA2");
        AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest
                ();
        AlipayFundTransToaccountTransferModel model = new AlipayFundTransToaccountTransferModel();
        // 鹿客家居的唯一提现流水号
        model.setOutBizNo(customerWalletRecord.getOrderNo());
        // 收款方账户类型。
        model.setPayeeType("ALIPAY_LOGONID");
        // 收款方账户。
        model.setPayeeAccount(zhifubao);
        // 转账金额
        DecimalFormat formater = new DecimalFormat("#0.#");
        formater.setRoundingMode(RoundingMode.FLOOR);
        logger.error(formater.format(Arith.mul(money, Arith.sub(1, 0.006))));
        model.setAmount(formater.format(Arith.mul(money, Arith.sub(1, 0.006))));
        // 付款方真实姓名
        model.setPayerShowName("郑州鹿客互联网科技有限公司");
        // 收款方真实姓名（最长支持100个英文/50个汉字）。
        model.setPayeeRealName(name);
        // 转账备注
        model.setRemark("顾客个人提现");
        // 加入请求头
        request.setBizModel(model);
        AlipayFundTransToaccountTransferResponse response = null;
        try {
            Thread.sleep(3000);
            response = alipayClient0.execute(request);
            if (response.isSuccess()) {// 请求成功
                // 请求成功，把该次请求插入数据库
                insertMoneyRecord(customerWalletRecord, customer, 1);
                // 返回已经处理成功信息
                JSONObject jsonObject = JSONObject.parseObject(response.getBody());
                logger.error(jsonObject.get("alipay_fund_trans_toaccount_transfer_response"));
                buluResult.setStatus(0);
                buluResult.setMessage("提现成功");
                // {"msg":"Success","pay_date":"2017-04-15
                //12:34:40 "," code ":" 10000 "," order_fee ":" 0.00 "," out_biz_no ":" xia12345678890 "," order_id ":"20170415110070001502310004692121 "," status ":" SUCCESS "}
            } else {
                if (response.getCode().equals("40004") && response.getSubCode().equals
                        ("PAYER_BALANCE_NOT_ENOUGH")) {
                    insertMoneyRecord(customerWalletRecord, customer, 2);
                    buluResult.setStatus(2);
                    buluResult.setMessage("提现申请中,请耐心等待...");
                    return buluResult;
                }
                BuluResult buluResult2 = alipayFundTransOrderQuery(customerWalletRecord,
                        customer);
                if (buluResult2.getStatus() == 0) {
                    buluResult.setStatus(0);
                    buluResult.setMessage("提现成功");
                } else {
                    // 返回转账失败信息
                    JSONObject jsonObject = JSONObject.parseObject(response.getBody());
                    logger.error(jsonObject.get
                            ("alipay_fund_trans_toaccount_transfer_response"));
                    buluResult.setStatus(1);
                    buluResult.setMessage(response.getSubMsg());
                }
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return buluResult;
    }

    /**
     * 提现业务的防止幂等现象
     */
    private BuluResult alipayFundTransOrderQuery(CustomerWalletRecord customerWalletRecord, Customer customer) {
        logger.error("=======================================顾客提现查看是否出现幂等现象 =========================================");
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                AlipayConfig.app_id, AlipayConfig.app_private_key, "json", "utf-8",
                AlipayConfig.alipay_public_key,
                "RSA2");
        BuluResult buluResult = new BuluResult();
        AlipayFundTransOrderQueryRequest request = new AlipayFundTransOrderQueryRequest();
        AlipayFundTransOrderQueryModel model = new AlipayFundTransOrderQueryModel();
        model.setOutBizNo(customerWalletRecord.getOrderNo());
        request.setBizModel(model);
        AlipayFundTransOrderQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
            if (response.isSuccess()) {
                logger.error("在支付宝找到了本次订单，说明已经转过了出现了幂等现象，更新数据库数据返回转账结束标志");
                        logger.error(response.getBody());
                // 请求成功，把该次请求插入数据库
                insertMoneyRecord(customerWalletRecord, customer, 1);
                // 返回已经处理成功信息
                logger.error(JSONObject.parseObject(response.getBody())
                        .get("alipay_fund_trans_toaccount_transfer_response"));
                buluResult.setStatus(0);
                buluResult.setMessage("提现成功");
                // {"msg":"Success","pay_date":"2017-04-15
                //12:34:40 "," code ":" 10000 "," order_fee ":" 0.00 "," out_biz_no ":" xia12345678890 "," order_id ":"20170415110070001502310004692121 "," status ":" SUCCESS "}
            } else {
                // 数据库中插入一条没有处理的提现记录(无论提现是否成功都要保存提现记录)
                insertMoneyRecord(customerWalletRecord, null, 0);
                // {"msg":"Business
                // Failed","code":"40004","sub_msg":"转账订单不存在 "," sub_code ":" ORDER_NOT_EXIST "}
                logger.error("在支付宝没有查到本次转账订单，本次转账在支付宝方没有处理也没有出现幂等现象");
                        JSONObject jsonObject = JSONObject.parseObject(response.getBody());
                logger.error(jsonObject.get("alipay_fund_trans_order_query_response"));
                buluResult.setStatus(1);
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return buluResult;
    }

    // 保存提现记录
    private void insertMoneyRecord(CustomerWalletRecord customerWalletRecord, Customer customer,
                                   Integer withdrawalStatus) {
        if (withdrawalStatus == 0) {// 申请提现
            customerWalletRecord.setStatus(withdrawalStatus);
            customerWalletRecord.setRecordEndTime(DateUtils.getDateTime());
            customerWalletRecord.setFinalLostMoney(customerWalletRecord.getWalletWithdrawals());
            customerWalletRecord.setIsDelete(0);
            customerWalletRecordService.insertCustomerWalletRecord(customerWalletRecord);
			/*
			 * moneyRecord.setWithdrawalStatus(withdrawalStatus);// 0代表提现没有被处理
			 * customerDao.insertMoneyRecord(moneyRecord);
			 */
        } else if (withdrawalStatus == 1) {// 提现完成
            customerWalletRecord.setStatus(withdrawalStatus);
            customerWalletRecord.setRecordEndTime(DateUtils.getDateTime());
            customerWalletRecord.setFinalLostMoney(customerWalletRecord.getWalletWithdrawals());
            customerWalletRecord.setIsDelete(0);
            customerWalletRecordService.insertCustomerWalletRecord(customerWalletRecord);
			/*
			 * moneyRecord.setWithdrawalStatus(withdrawalStatus);// 1代表提现已经处理
			 * customerDao.insertMoneyRecord(moneyRecord);
			 */
            // 更新工人提现后的金额
            Double newWlallet = Arith.sub(customer.getWallet(),
                    customerWalletRecord.getWalletWithdrawals());
            Map<String, Object> map = new HashMap<>();
            map.put("customerId", customerWalletRecord.getCustomerId());
            map.put("wallet", newWlallet);
            customerDao.updateWalletComple(map);
        } else if (withdrawalStatus == 2) {// 付款方余额不足
            customerWalletRecord.setStatus(withdrawalStatus);
            customerWalletRecord.setFinalLostMoney(customerWalletRecord.getWalletWithdrawals());
            customerWalletRecord.setIsDelete(0);
            customerWalletRecordService.insertCustomerWalletRecord(customerWalletRecord);
			/*
			 * moneyRecord.setWithdrawalStatus(withdrawalStatus);// 0代表提现没有被处理
			 * customerDao.insertMoneyRecord(moneyRecord);
			 */
            // 更新工人提现后的金额
            Double newWlallet = Arith.sub(customer.getWallet(),
                    customerWalletRecord.getWalletWithdrawals());
            Map<String, Object> map = new HashMap<>();
            map.put("customerId", customerWalletRecord.getCustomerId());
            map.put("wallet", newWlallet);
            customerDao.updateWalletComple(map);
        }
    }

    /**
     * 如果工人提现但提现标志WithdrawalStatus=2 需要上传照片 调用该接口 本次存放的金融账号在表格中设置为1（默
     * 认）
     * 目前只支持支付宝，没有传类似type的的字段没有办法判断添加提现到什么地方
     */
    @Transactional
    public BuluResult auditPresentation(HttpServletRequest request, String alipyCode, String IdCard,
                                        String faceIDCard,
                                        String backIDCard) {
        BuluResult buluResult = new BuluResult();
        // if (faceIDCard == null || backIDCard == null) {
        // buluResult.setStatus(1);
        // buluResult.setMessage("请先上传有效照片");
        // return buluResult;
        // }
        // String sign = request.getParameter("sign");
        // Integer customerId =
        // Integer.parseInt(JedisUtil.getSessionIDForApp(sign, 5));
        // Customer customer = customerDao.getCustomerById(customerId);
        // //如果走这个接口，说明工人目前还没有提现能力
        // List<BankCard> list = customerDao.selectNoUseBank(customerId);
        // if(null!=list && list.size()>0){
        // updateAuditPresentation(list,customerId,customer);
        // }
        // BankCard bankCard = new BankCard();
        // bankCard.setBoundBank("支付宝");
        // bankCard.setAlipayNum(alipyCode);
        // bankCard.setPeopleId(customerId);// 工人账户
        // bankCard.setStatus(1);// 默认
        // bankCard.setType(0);// 0代表工人
        // bankCardDao.insertBankCard(bankCard);
        // if (null == customer.getFaceIdCard() ||
        // customer.getFaceIdCard().equals("")) {
        // customer.setFaceIdCard(faceIDCard);
        // customer.setBackIdCard(backIDCard);
        // customer.setIdCard(IdCard);
        // customer.setWithdrawalStatus(0);
        // customer.setAlipayNum(alipyCode);
        // customerDao.updateCustomer(customer);
        // }
        // buluResult.setData(customer);
        // buluResult.setStatus(0);
        // buluResult.setMessage("提现正在审核中....");
        return buluResult;
    }

    /**
     * 清理之前的无效提现数据
     *
     * @param list
     * @param customerId
     */
    private void updateAuditPresentation(List<BankCard> list, Integer customerId, Customer worker) {
        // JSONArray idArray= new JSONArray();
        // for(int a = 0;a<list.size();a++){
        // idArray.add(list.get(a).getBankCardId());
        // }
        // //将其对应的id给为删除状态
        // workerDao.updateNoUseBank(idArray);
        // //将工人之前对应保存的也都清空,并且设置为空
        // if(null!=worker.getFaceIdCard() &&
        // !("".equals(worker.getFaceIdCard())) ){
        // worker.setFaceIdCard(null);
        // worker.setBackIdCard(null);
        // worker.setIdCard(null);
        // worker.setWithdrawalStatus(2);
        // worker.setAlipayNum(null);
        // workerDao.updateWorker(worker);
        // }
    }

    // 添加评价 workerEvation="[{workerId:'',star:,type:,indentId:},{}]"
    // public BuluResult submitEvaluation(HttpServletRequest request, String
    // workerEvation,Integer goodsId, String content, Integer star1, Integer
    // sampleId, String imgs) {
    // BuluResult buluResult = new BuluResult();
    // Integer customerId = getIdFromRedis(request);
    //
    // if (goodsId != null) {
    // Evaluation evaluation = new Evaluation();
    // evaluation.setContent(content);//评价内容
    // evaluation.setCustomerId(customerId);//顾客ID
    // evaluation.setSampleId(sampleId);//产品ID
    // evaluation.setStar(star1);//星级
    // evaluation.setType(0);//产品评价
    // evaluation.setEvaTime(new Date());//评价时间
    // customerDao.insertGEvaluation(evaluation);
    // customerDao.updateGoodsEva(goodsId);
    // Integer indentId = Integer.parseInt(request.getParameter("indentId"));
    // List<Integer> goodsIds = customerDao.getGoodsIdsByIndentId(indentId);
    // List<Goods> goods = customerDao.getGoodByIndentId(goodsIds);
    // boolean isEva = true;
    // for (Goods goods2 : goods) {
    // if (goods2.getIsEvaluation() != 1) {//未评价商品
    // isEva = false;
    // }
    // }
    // if (isEva) {
    // Map<String, Object> map = new HashMap<>();
    // map.put("indentId", indentId);
    // map.put("status", 15);
    // customerDao.updateIndent(map);
    // }
    // if (imgs != null) {
    // JSONArray imgArray = JSONArray.parseArray(imgs);
    // // JSONObject we = JSONObject.parseObject(imgs);
    // for (int a = 0; a < imgArray.size(); a++) {
    // Map<String, Object> imgMap = new HashMap<String, Object>();
    // imgMap.put("img", imgArray.get(a));
    // imgMap.put("evaluationId", evaluation.getEvaluationId());
    // customerDao.insertGPicture(imgMap);
    // }
    // }
    // if (workerEvation != null) {
    // JSONArray WK = JSONArray.parseArray(workerEvation.toString());
    // for (int a = 0; a < WK.size(); a++) {
    // Map<String, Object> wkMap = WK.getJSONObject(a);
    // wkMap.put("evaTime", new Date());
    // customerDao.insertWEvaluation(wkMap);
    // Map<String, Object> map = new HashMap<>();
    // map.put("indentId", (Integer) wkMap.get("indentId"));
    // map.put("status", 15);
    // customerDao.updateIndent(map);
    // }
    // }
    // buluResult.setStatus(0);
    // buluResult.setMessage("评价完成!!!");
    // }else if (workerEvation != null) {
    // JSONArray WK = JSONArray.parseArray(workerEvation.toString());
    // for (int a = 0; a < WK.size(); a++) {
    // Map<String, Object> wkMap = WK.getJSONObject(a);
    // customerDao.insertWEvaluation(wkMap);
    // Map<String, Object> map = new HashMap<>();
    // map.put("indentId", (Integer) wkMap.get("indentId"));
    // map.put("status", 15);
    // customerDao.updateIndent(map);
    // }
    // buluResult.setStatus(0);
    // buluResult.setMessage("评价完成!!!");
    // } else {
    // buluResult.setStatus(1);
    // buluResult.setMessage("传入参数有误!!!");
    // }
    // return buluResult;
    // }

    // 更新配件的数目
    // public BuluResult
    // @Override
    // public BuluResult insertIndent(HttpServletRequest request, String goods)
    // {
    // TODO Auto-generated method stub
    // BuluResult buluResult = new BuluResult();
    // Map<String, Object> map = new HashMap<>();
    // //获取redIs中的用户id
    // Integer customerId =getIdFromRedis(request);
    // //解析用户端的goods数据
    // JSONObject goodsObject = JSONObject.parseObject(goods);
    // JSONArray goodsArray = goodsObject.getJSONArray("goodsAndAcc");
    // //判断业务类型
    // Integer self_measuring = Integer.parseInt((String)
    // goodsObject.get("zizhu"));
    // //self_measuring=0平台测量
    // //self_measuring=1自主测量
    // if (self_measuring != 1) {
    // // goods:[{goods:{},},]
    // // 测量订单信息封装
    // Date beginTime = new Date();
    // Indent indent = new Indent();
    // indent.setBeginTime(beginTime);
    // indent.setIndentType(0);
    // indent.setSubscribeTime(goodsObject.getDate("subscribeTime"));
    // indent.setType(0);
    // indent.setStatus(0);
    // indent.setCuAdId(1);
    // indent.setCustomerId(customerId);
    // customerDao.insertIndent(indent);
    // // 生成订单, 并得到订单号
    // for (int i = 0; i < goodsArray.size(); i++) {
    // // {goodsId:{},}
    // Integer goodsId = goodsArray.getInteger(i);
    // // 修改商品为不是购物车商品
    // customerDao.updateGoodsCar(goodsId);
    // Map<String, Object> map1 = new HashMap<>();
    // map1.put("goodsId", goodsId);
    // map1.put("indentId", indent.getIndentId());
    // customerDao.insertGood_Indent(map1);
    // }

    // Integer roomNumB = customerDao.selectDistinct(indent.getIndentId())
    // + customerDao.selectOtherRoom(indent.getIndentId());
    // Map<String, Object> room = new HashMap<>();
    // room.put("indentId", indent.getIndentId());
    // room.put("roomNumB", roomNumB);
    // // 计算测量费 查询客户应交定金 这里
    // String city = (String) goodsObject.get("city");
    // Map<String, Object> cliang = customerDao.selectCLiang(city);
    // Double indentPrice = 0.0;
    // if ((Integer) cliang.get("roomNumber") >= roomNumB) {//
    // 所需测量房间数小于设定的房间数
    // indentPrice = (Double) cliang.get("measureM");
    // } else {// 测量费需加钱
    // indentPrice = (Double) cliang.get("measureM")
    // + (Double) cliang.get("dmeasureM") * (Arith.sub(roomNumB, (Integer)
    // cliang.get("roomNumber")));
    // }
    // room.put("indentPrice", indentPrice);
    // // 测量费估计也得在这加(修改插入语句中加入测量费)
    // customerDao.updateIndentRoom(room);
    //
    // // 订单id得到所有的商品id
    // List<Integer> goods_indents = customerDao.getGoodIdByIndentId((int)
    // indent.getIndentId());
    // List<Map<String, Object>> samples = new ArrayList<>();
    // for (Integer goodsId : goods_indents) {
    // // 得到样品id和样品图片
    // Map<String, Object> img = customerDao.getSampleByGoodId2(goodsId);
    // List<Map<String, Object>> acces =
    // customerDao.getGoods_AccByGoodsId(goodsId);
    // img.put("acces", acces);
    // samples.add(img);
    // }
    // map.put("beginTime", indent.getBeginTime());
    // map.put("indentPrice", indent.getIndentPrice());
    // map.put("indentId", indent.getIndentId());
    // map.put("deposit", indent.getDeposit());
    // map.put("status", indent.getStatus());
    // map.put("samples", samples);
    // buluResult.setStatus(0);
    // buluResult.setData(map);
    // }
    // else {
    // Date beginTime = new Date();
    // Indent indent = new Indent();
    // indent.setBeginTime(beginTime);
    // indent.setType(4);// 4为经销商自主测量
    // indent.setStatus(0);
    // indent.setCustomerId(customerId);
    // // 测量房间数
    // indent.setIndentType(0);
    // customerDao.insertIndent(indent);
    // for (int i = 0; i < goodsArray.size(); i++) {
    // // {goodsId:{},}
    // Integer goodsId = goodsArray.getJSONObject(i).getInteger("goodsId");
    // Map<String, Object> map1 = new HashMap<>();
    // map1.put("goodsId", goodsId);
    // map1.put("indentId", indent.getIndentId());
    // customerDao.insertGood_Indent(map1);
    // }
    // Integer roomNumB = customerDao.selectDistinct(indent.getIndentId())
    // + customerDao.selectOtherRoom(indent.getIndentId());
    // Map<String, Object> room = new HashMap<>();
    // room.put("indentId", indent.getIndentId());
    // room.put("roomNumB", roomNumB);
    // customerDao.updateIndentRoom(room);
    // buluResult.setStatus(0);
    // }
    // return buluResult;
    // 这个执行完用户如果支付定金则需要一个接口修改订单状态和一些信息 还需修改商品属性改为不是购物车商品
    // return null;
    // }

    // for (int a = 0; a < jsonArray.size(); a++) {
    // Integer goodsId = (Integer) jsonArray.get(a);
    // List<Integer> list = customerDao.selectAZpeijian(goodsId);// 某个物品安装所需配件
    // for (int b = 0; b < list.size(); b++) {
    // Map<String, Object> peijian = customerDao.selectAccnumber(list.get(b));//
    // 配件属性
    // if ("粘带".equals(peijian.get("acc")) || "魔术轨".equals(peijian.get("acc")))
    // {// 配件的配件中有粘带或魔术轨则轨道数算的时候加一
    // if ((Double) map.get("miNumber") >= (Double) peijian.get("saleNumber"))
    // {// 符合规定米数
    // // 不用加钱
    // goodsAZ += (Double) map.get("installM") * ((Integer)
    // peijian.get("number") + 1);// 加上配件的配件的
    // // 算一杆
    // } else {// 不符合规定米数 需加钱 超过几米 乘以超出的单价
    // // 超过的需加多少钱
    // Double money = Arith.sub((Double) peijian.get("saleNumber"), (Double)
    // map.get("miNumber"))
    // * (Double) map.get("dinstallM");
    // goodsAZ += ((Double) map.get("installM") + money) * ((Integer)
    // peijian.get("number") + 1);// 加上配件的配件的
    // // 算一杆
    // }
    // } else {
    // if ((Double) map.get("miNumber") >= (Double) peijian.get("saleNumber"))
    // {// 符合规定米数
    // // 不用加钱
    // goodsAZ += (Double) map.get("installM") * (Integer)
    // peijian.get("number");// 加上配件的配件的
    // // 算一杆
    // } else {// 不符合规定米数 需加钱 超过几米 乘以超出的单价
    // // 超过的需加多少钱
    // Double money = Arith.sub((Double) peijian.get("saleNumber"), (Double)
    // map.get("miNumber"))
    // * (Double) map.get("dinstallM");
    // goodsAZ += ((Double) map.get("installM") + money) * (Integer)
    // peijian.get("number");// 加上配件的配件的
    // // 算一杆
    // }
    // }
    // }
    // }

    /**
     * 功能：添加配件部分信息
     *
     * @param request
     * @param accsList
     * @param goods
     */
    // public void addGoodsSpecial(HttpServletRequest request,JSONArray
    // accsList,Integer type){
    // for (int j = 0; j < accsList.size(); j++) {
    // Goods accssData = LuKeBeanUtil.fromJSONObjectToBean(
    // JSONObject.parseObject(accsList.getString(j)),Goods.class); //配件信息
    // // 先生成商品,然后再添加关系表
    // Goods goods=addGoods(request, accssData,0,type); //保存配件部分商品信息
    // Goods_special special=LuKeBeanUtil.fromJSONObjectToBean(
    // JSONObject.parseObject(accsList.getString(j)),Goods_special.class);
    // //配件信息
    // if(special !=null){
    // if(goods.getGoodsId() !=null){
    // special.setGoodsId(goods.getGoodsId());
    // special.setGoodsIdChild(goods.getGoodsId() * 10 + j);
    // }
    // if (goods.getInstallCase() != null && goods.getInstallCase() == 1) {//
    // 布纱同一位置安装
    // Goods_special specialYarn=(Goods_special)special.clone();
    // specialYarn.setType(1);//纱
    // saveGoodsSpecial(specialYarn);
    // }
    // }
    // saveGoodsSpecial(special);
    // }
    // }

    /**
     * 功能：返回待支付的订单
     *
     * @param request
     * @return
     */
    // public BuluResult clickPaying(HttpServletRequest request) {
    // System.out.println("___________start_____________________");
    // BuluResult buluResult = new BuluResult();
    // Integer customerId = getIdFromRedis(request);
    // List<Integer> status = new ArrayList<Integer>();
    // status.add(4);// 待支付
    // Map<String, Object> inParames = new HashMap<String, Object>();
    // inParames.put("status", status);
    // inParames.put("customerId", customerId);
    // List<Indent> indents = customerDao.getDiffrStatusIndents(inParames);
    // // 返回订单数据
    // System.out.println("ber indents:"+indents);
    // List<Map<String, Object>> indentsList = getOrdersData(indents);
    // System.out.println("aft indents:"+indentsList);
    // // List<Map<String, Object>> ordersList =
    // // customerDao.selectStatus7((Integer) customerId);
    // // Map<String, Object> map = new HashMap<String, Object>();
    // // map.put("indent", indentsList);
    // // map.put("order", ordersList);
    // buluResult.setStatus(0);
    // buluResult.setMessage("返回待支付订单");
    // buluResult.setData(indentsList);
    // return buluResult;
    // }
    //
    // public static void main(String[] args) {
    // List<Integer> o =new ArrayList<>();
    // System.out.println(JSONObject.toJSONString(o));
    // }

    /**
     * 商品信息Sample的录入到数据可 {商品信息"SampleContent":{ 商品json对象"sample":{"
     * sampleDescribe":"" , "structure":"","holePrice":"".. },
     * 风格"styles":[{"styleId":""},{}..],
     * 适用场景"locations":[{"locationId":""},{}..],图片json对象"pictures":[{},{}..],面料使用方式json对
     * 象"composition":[{},{}..]}}
     * {商品信息"SampleContent":{"sample":{"sampleId":"","sampleDescribe":"" ,
     * "structure":"","holePrice":"","holeSpecPrice"
     * <p>
     * :"","zhePrice":"","zheSpecPrice":"","sale":"","saleCount":"","sampleImg":"","type":"","special":"","
     * swag":"",
     * "minWide":"","maxWide":"","minHigh":"","maxHigh":"","series":"","seriesSample":"",
     * <p>
     * "firstProfit":"","fSProfit":"","secondProfit":"","ziyingProit":"","fptId":"","material":"","accessoriesTypeId"
     * :"","price":"","brand":"",
     * <p>
     * "chargeUnit":"","suitableObject":"","washing":"","isInstall":"","ssPrice":"","llPrice":"","isSty":"","times_fo
     * ld":"","hem":"","shading":"","shadeDesign":"","functions":"","installation":"","methodUse":"","huodong":""},
     * 风格"styles":[{"styleId":""},{}..],适用场景"locations":[{"locationId":""},{}..],
     * 图片json对象"pictures":
     * [{"pictureId":"","img":"","evaluationId":"","dealerId":"","measureGoods_special":"","installGoods_special":"",
     * "maintainGoods_special":"","sampleId":"","graphicDetails":"","graphicDetailsPX":"",
     * <p>
     * "styleDescription":"","styleDescriptionPX":"","guidance":"","guidancePX":"","other":"","appId":"","isDeleted":
     * ""},{图片json对象}..],
     * 面料使用方式json对象"compositions":
     * [{"compositionId":"","serialnumber":"","material":"","breadth":"","spur":"","breadthStatus":"","inverte":"","p
     * urchasePrice":"","supplierId":"","putTogether":"","putNumber":"","type":"",
     * "sampleId":"","produceArea":"","price":""},{面料使用方式json对象}..]}}
     */

    public BuluResult insert_Sample(HttpServletRequest request, String sampleContent) {
        BuluResult buluResult = new BuluResult();
        JSONObject object = JSONObject.parseObject("sampleContent");
        if (null != object) {
            // 获取商品json对象转换成javaBean实体
            Sample sample = LuKeBeanUtil.fromJSONObjectToBean(object.getJSONObject("sample"),
                    Sample.class);
            if (null != sample) {
                // 将商品Sample插入到数据可返回主键

                // 获取商品风格jsonArray并转换成数组
                JSONArray stylelist = object.getJSONArray("styles");
                Integer[] styles = (Integer[]) stylelist.toArray();

                // 获取商品适用场景jsonArray并转换成数组
                JSONArray locationlist = object.getJSONArray("locations");
                Integer[] locations = (Integer[]) stylelist.toArray();

                // 获取图片jsonArray
                JSONArray pictureArray = object.getJSONArray("pictures");
                // 将picture装换为javaBean并放入到集合中
                List<Picture> locatinlist = new ArrayList<Picture>();
                for (int i = 0; i < pictureArray.size(); i++) {
                    locatinlist.add(LuKeBeanUtil.fromJSONObjectToBean
                            (pictureArray.getJSONObject(i), Picture.class));
                }

                // 获取面料使用方式jsonArray
                JSONArray compositionArray = object.getJSONArray("compositions");
                // 将composition装换为javaBean并放入到集合中
                List<Composition> compositionlist = new ArrayList<Composition>();
                for (int i = 0; i < compositionArray.size(); i++) {
                    compositionlist.add(
                            LuKeBeanUtil.fromJSONObjectToBean
                                    (compositionArray.getJSONObject(i), Composition.class));
                }
            }
        }
        return null;
    }

    /**
     * 查询商品添加页面参数
     */
    public BuluResult addSampleParam() {
        long startTime = System.currentTimeMillis();
        // 准备返回参数
        BuluResult buluResult = new BuluResult();
        // 返回参数
        Map<String, Object> map = new HashMap<String, Object>();

        // 查询商品风格基础数据
        map.put("style", customerDao.selectStyles());
        // 查询商品适应场景基础数据
        map.put("location", customerDao.selectLocations());
        // 成品帘类型
        map.put("finishproducttype", customerDao.selectFinishproducttypes());
        // 配件类型基础数据
        map.put("accessoriestype", customerDao.selectAccessoriestypes());
        // 查询材质
        addDicParam("cloth", map);
        // 查询系列
        addDicParam("series", map);
        // 查询幅宽
        addDicParam("breadth", map);
        // 查询功能 遮光|透景
        addDicParam("function", map);
        // 查询款式类型 打孔|韩褶
        addDicParam("style_type", map);
        // 查询结构 对开|拼接
        addDicParam("structure", map);
        // 查询布艺颜色
        addDicParam("colour", map);
        // 查询布艺类型 主布|配布
        addDicParam("cloth_type", map);
        // 查询窗帘 定高|不定
        addDicParam("change_high", map);
        // 查询洗涤说明
        addDicParam("Wash_instruc", map);
        // 查询倍褶
        addDicParam("times_fold", map);
        // 查询洗涤说明
        addDicParam("spur", map);
        // 查询洗涤说明
        addDicParam("shading", map);
        long stopTime = System.currentTimeMillis();
        System.out.println("耗时==" + (stopTime - startTime));
        buluResult.setStatus(0);
        buluResult.setData(map);
        return buluResult;
    }

    /**
     * /查询字典表商品添加其他参数
     *
     * @param dicName
     * @param map
     * @return
     */
    @SuppressWarnings("unused")
    private Map<String, Object> addDicParam(String dicName, Map<String, Object> map) {
        // 字典表参数查询传入参数
        Map<String, Object> list = new HashMap<>();
        list.put("dic_name", dicName);
        // 查询字典表数据
        List<Map<String, Object>> dics = customerDao.selectDictionary(list);
        map.put(dicName, dics);
        return map;

    }

    /**
     * /字典表新属性的添加
     */

    public BuluResult dic_insert(Dictionary dictionary) {
        // 准备返回参数
        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        if (null != dictionary) {

            customerDao.dic_insert(dictionary);
            buluResult.setData(dictionary);
        } else {
            buluResult.setStatus(1);
            buluResult.setMessage("添加信息数据有误，请检查填写数据");
        }

        return buluResult;
    }

    // 查询字典表细分参数数据
    public BuluResult selectDictionarybyParam(Map<String, Object> map) {
        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        // 根据dic_name和dic_value查字典详情布|麻，棉
        buluResult.setData(customerDao.selectDictionarybyParam(map));
        return buluResult;

    }

    @Override
    public BuluResult insert_Sample() {
        // TODO Auto-generated method stub
        return null;
    }

    // 修改用户信息
    @Override
    public BuluResult updateUserInfo(HttpServletRequest request) {
        // TODO Auto-generated method stub
        String name = request.getParameter("name");
        String zhifubao = request.getParameter("zhifubao");
        Map<String, Object> map = new HashMap<>();
        map.put("customerId", getIdFromRedis(request));
        map.put("name", name);
        map.put("zhifubao", zhifubao);
        customerDao.updateUserInfo(map);
        BuluResult buluResult = new BuluResult();
        buluResult.setStatus(0);
        buluResult.setMessage("信息修改成功");
        return buluResult;
    }

    @Override
    public BuluResult selectSamplesOfStyles(HttpServletRequest request, Map<String, Object> parames) {
        // TODO Auto-generated method stub
        BuluResult buluResult = new BuluResult();
        Integer page = (Integer) parames.get("page") * 10 - 9;
        parames.put("page",page);
        List<Sample> list = sampleDao.selectSamplesOfStyle(parames);
        Double measureMoneyOff = customerDao.selectTerritoryByType(8).getMoney();
        Double installMoneyOff = customerDao.selectTerritoryByType(9).getMoney();
        for (Sample sample:list) {
            sample.setMeasureMoneyOff(measureMoneyOff);
            sample.setInstallMoneyOff(installMoneyOff);
        }
        buluResult.setStatus(0);
        buluResult.setMessage("筛选成功");
        buluResult.setData(list);
        return buluResult;
    }

    
	@Override
	public BuluResult subordinate(HttpServletRequest request, HttpSession session,String phone, String vertifyCode,Integer customerId,Integer identity) {
		//判断用户是否已经注册
		// TODO Auto-generated method stub
		BuluResult buluResult=new BuluResult();
		if(session.getAttribute(com.cn.bulu.constant.Const.SESSION_VERIFY_CODE) ==null || !(vertifyCode.equals(session.getAttribute(com.cn.bulu.constant.Const.SESSION_VERIFY_CODE).toString()))){
			buluResult.setStatus(1);
			buluResult.setMessage("验证码错误或已过时,请重新发送");
			return buluResult;
		}
		Customer  currentCustomer=this.getCustomerById(customerId);//当前登录用户
		Customer registCustomer=customerDao.selectCustomerInfoOfDealer(phone);
		if(currentCustomer !=null){//注册用户为经销商或者推广员
			//判断当前用户是否已注册后台
			User parentUser=null;
			if(currentCustomer.getPhone() !=null && !("".equals(currentCustomer.getPhone()))){
				parentUser =userDao.SelectUser(currentCustomer.getPhone());
			}
			if(parentUser !=null){
				if(registCustomer !=null){
							//修改customer
							if("0".equals(registCustomer.getVertification())){
								registCustomer.setVertification(String.valueOf(identity));
								customerDao.updateCustomer(registCustomer);
							}	
							//如果经销商不存在的话
//							if(dealerDao.getDealerNumber(phone)==0){
//								Dealer dealer=new  com.cn.bulu.pojo.Dealer.Builder().phone(phone)
//										.name(registCustomer.getName()).referrer(currentCustomer.getPhone())
//										.wallet(registCustomer.getWallet()).boundBank(registCustomer.getBoundBank())
//										.bankNumber(registCustomer.getBankNumber()).recordPassword(phone).type(Integer.valueOf(registCustomer.getVertification()))
//										.buider();
//								//添加
//								dealerDao.insertDealer(LuKeBeanUtil.fromBeanToMap(dealer));
//							}
							//如果账号不存在的话，建立账号
							if(userDao.SelectUserExit(registCustomer.getPhone())==0){
								User user=new User(registCustomer.getPhone(), registCustomer.getName(), registCustomer.getNickName(), registCustomer.getPassword(), 
										parentUser.getUserId(), registCustomer.getVertification(), registCustomer.getWeiyi(), registCustomer.getWallet(), registCustomer.getBankName(), 
										registCustomer.getBankNumber(), registCustomer.getPassword());
								userDao.insertUser(user);
							}
							buluResult.setStatus(0);
							 String message="2".equals(registCustomer.getVertification()) ? "欢迎你的加入，你已经是代理商"+currentCustomer.getName()+"名下的经销商"
									: ("3".equals(registCustomer.getVertification())?"欢迎你的加入，你已经是经销商"+currentCustomer.getName()+"名下的推广员":"很遗憾，操作失败");
							buluResult.setMessage(message);
							return buluResult;
				}else{
					buluResult.setStatus(1);
					buluResult.setMessage("请先注册鹿客家居！");
					return buluResult;
				}
			}
		}
		buluResult.setStatus(1);
		buluResult.setMessage("很遗憾，操作失败");
		return buluResult;
	} 

	@Override
	public BuluResult recordUserAndCustomer(HttpServletRequest request, HttpSession session,String phone, String vertifyCode,Integer customerId){
		BuluResult buluResult=new BuluResult();
		if(session.getAttribute(com.cn.bulu.constant.Const.SESSION_VERIFY_CODE) ==null || !(vertifyCode.equals(session.getAttribute(com.cn.bulu.constant.Const.SESSION_VERIFY_CODE).toString()))){
			buluResult.setStatus(1);
			buluResult.setMessage("验证码错误或已过时,请重新发送");
			return buluResult;
		}
		buluResult.setStatus(0);
		return buluResult;
	}

	public List<Map<String, Object>> getAccessTypeContentOfGoods(Integer goodsId) {
		if (goodsId == null)
			return null;
		List<Map<String, Object>> access = customerDao.getAccessTypeContentOfGoods(goodsId);
		return access;
	}
	
	@Override
	public BuluResult isReigister(String userName){
		BuluResult b=new BuluResult();
		int n=userDao.SelectUserExit(userName);
		if(n>0){
			b.setStatus(1);
			b.setMessage("你已经是平台的用户");
			return b;
		}
		//判断该手机号是否注册鹿客家居
		Map<Object,Object>map=new HashMap<>();
		map.put("phone", userName);
		int m=customerDao.selectCustomer(map);
		if(m==0){
			b.setStatus(2);
			b.setMessage("还未注册鹿客家居");
			return b;
		}
		b.setStatus(0);
		return b;
	}

	/**
	 * 功能：计算安装费用
	 * 
	 * @param city
	 * @return
	 */
	public Double countAzhuangMoney(String city, Double indentPrice, List<Integer> list, Integer shouldMeasure) {
		if (city == null || "".equals(city) || list == null || list.size() == 0)
			return indentPrice;
		Double installStartingFare = 0.0;// 安装起步价
		for (Integer id : list) { // 遍历订单下所有商品
			Goods goods = goodsDao.selectGoodsById(id);
			if (goods == null)
				return indentPrice;
			List<Map<String, Object>> parsAcc = new ArrayList<Map<String, Object>>();
			if (goods.getType() == 2) {// 配件
				List<Map<String, Object>> parsList = customerDao.getParsGoods(id);
				parsAcc.addAll(parsList);
			} else {// 布艺帘-成品帘
				List<Map<String, Object>> parsList = customerDao.getParsGoodsIdsByGoodsId(id);
				parsAcc.addAll(parsList);
			}
			if (parsAcc.size() == 0)
				return indentPrice;
			for (Map<String, Object> pars : parsAcc) {// 遍历配件
				Map<String, Object> paras = new HashMap<>();
				paras.put("city", city);
				paras.put("ttype", 1);
				paras.put("ctype", pars.get("accessoriesType"));
				Cost_rules rule = customerDao.selectAPriceByCity(paras); // 所在城市安装情况
				if (rule == null)
					continue;
				if (installStartingFare == 0.0)
					installStartingFare = rule.getInstallStartingFare();// 起步价

				Integer number = Integer.valueOf(pars.get("number") == null ? "0" : pars.get("number").toString());// 单双（单杆/双杆）

				Double base = (number == 1 ? rule.getSingle() : (number == 2 ? rule.getDoubleDeck() : null));// 安装基础费用
				if (base != null) {
					if (shouldMeasure == 0) {// 按照3.5*4计算
						indentPrice += base;
					} else {
						Double width = Double.valueOf(pars.get("wide") == null ? "0" : pars.get("wide").toString());// 实际宽
						Double heigh = Double.valueOf(pars.get("high") == null ? "0" : pars.get("high").toString());// 实际高
						if (width == 0.0 || heigh == 0.0)
							return indentPrice;

						Double widthBasisMeter = rule.getWidthBasisMeter(); // 基础宽
						Double heightBasisMeter = rule.getHeightBasisMeter();// 基础高

						Double widthBeyondMeter = rule.getWidthBeyondMeter();// 超出宽（米）
						Double heightBeyondMeter = rule.getHeightBeyondMeter();// 超出高（米）

						Double heightBeyondUnitPrice = rule.getHeightBeyondUnitPrice();// 超出高加价
						if (widthBasisMeter == null || heightBasisMeter == null || widthBeyondMeter == null
								|| heightBeyondMeter == null || heightBeyondUnitPrice == null || widthBasisMeter <= 0
								|| heightBasisMeter <= 0 || widthBeyondMeter <= 0 || heightBeyondMeter <= 0
								|| heightBeyondUnitPrice <= 0) {
							return indentPrice;
						}
						// 超出基础高，重新算Base价格;
						if (heigh > heightBasisMeter) {
							base += Math.ceil((heigh - heightBasisMeter) / heightBeyondMeter) * heightBeyondUnitPrice;
						}
						// 超出宽的加倍累计
						if (width <= widthBasisMeter) {
							indentPrice += base;
						} else {
							indentPrice += base * (Math.ceil((width - widthBasisMeter) / widthBeyondMeter) + 1);
						}
					}
				}
			}
		}
		// 返回安装费
		if (indentPrice != 0.0 && indentPrice < installStartingFare) {
			indentPrice = installStartingFare;
		}
		System.out.println("indentPrice:" + indentPrice);
		return indentPrice;
	}

	@Override
	public String getQRCode(HttpServletRequest request) {
		// TODO Auto-generated method stub
		return null;
	}
}
